繁体   English   中英

如何用 plotly 在 R 中的两个给定点之间画一条线?

[英]How to draw a line between two given points in R with plotly?

我正在尝试使用加密货币(CC)价格的高点和低点绘制某种趋势线。 我正在使用的第一个库:

library(tidyverse)
library(reshape2)
library(lubridate)
library(TTR)
library(binancer)
library(plotly)

由于我在许多 CC 中进行选择,我正在使用下一个方案来实现某种自动化。 对于这个例子,我使用比特币 (BTC)。 以下代码将检索 4 小时时间范围内的比特币数据。 我将“horas”设置为 900 以获得 225 个观察值:

nombre <- "BTC"
tiempo <- "4h"
horas <- 900

data <- binance_klines(paste0(nombre,"USDT"), interval = paste0(tiempo), 
    start_time=Sys.time()-hours(paste0(as.numeric(horas))), end_time=Sys.time())%>%
    select(open_time, open, high, low, close, volume, trades)%>%
    rename(time=1)

接下来,我得到低点和高点,以使用这些数据绘制我想要的线条。 如您所见,我为高点和低点选择了两个点:

lows <- arrange(data, low)%>%
    slice(c(which.min(low), which.max(low)))%>%
    arrange(time)

highs <- arrange(data, high)%>%
    slice(c(which.max(high), which.min(high)))%>%
    arrange(time)

我还添加了一些简单的移动平均线 (SMA)。 我的 sma 数据库是我的 plot 的来源:

data%>%
    mutate(SMA_5= SMA(close, 5), SMA_10= SMA(close,10), SMA_20= SMA(close,20)) -> sma

我正在尝试使用 add_segments 来绘制我想要的低点线(如果这可行,我将对高点使用相同的代码)但我遇到了一些错误:

sma %>% plot_ly(x = ~time, type="candlestick",
                       open = ~open, close = ~close,
                       high = ~high, low = ~low) %>%
    add_lines(x = ~time, y= ~SMA_5,  line = list(color = "gold", width = 2), inherit = F,
                name = "SMA 5", showlegend=T)%>%
    add_lines(x = ~time, y= ~SMA_10,  line = list(color = "deeppink", width = 2), inherit = F,
                name = "SMA 10", showlegend=T)%>%
    add_lines(x = ~time, y= ~SMA_20,  line = list(color = "purple", width = 2), inherit = F,
                name = "SMA 20", showlegend=T)%>%
    add_segments(
                x = ~lows[1,1], xend = ~lows[2,1], 
                y = ~lows[1,4], yend = ~lows[2,4], color="black")%>%
    plotly::layout(title = paste0(nombre, " Simple Moving Average, ", tiempo),
        xaxis= list(title="Time", rangeslider = list(visible = F)), yaxis = list(title = "Price"),
        sliders=list(visible=F)) -> sma_plot

sma_plot

Error in `*tmp*`[[jj]] : subscript out of bounds 

知道我做错了什么吗? 任何反馈将不胜感激。

如果您试图在两个坐标之间画一条线,只需使用与其他线相同的图案即可。

add_lines(inherit = F, data = lows, x = ~time, y = ~low, 
          name = "Lows, line = list(color = "black")) 

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM