ggplotly 中的箱线图

BoxPlot in ggplotly

我正在尝试使用 plotly 库在 R 中绘制时间序列箱线图,但是我需要能够完全控制 ymin、ymax、ylow 等

它在 ggplot2 中呈现得非常好,尽管有大量警告。它无法在 ggplotly

中呈现

这是我的。

msft = read.csv("http://ichart.finance.yahoo.com/table.csv?s=MSFT", 
            header=TRUE, 
            sep=",")
msft$Date
msftF = msft %>% tbl_df() %>% filter(as.Date(Date) > as.Date("2016-01-01"))     %>% na.omit()
msftF %>%
  ggplot(aes(x = factor(Date), ymin = Low, lower = Open, middle = Close,     upper = Close, ymax = High)) +
  geom_boxplot() +
  geom_boxplot(stat = "identity") 

您可以使用 quantmod 包执行此操作。

尝试以下操作:

library(quantmod)
getSymbols("MSFT")
candleChart(MSFT,multi.col=TRUE,theme='white') 

如果您不需要所有这些,您可以 trim 将 MSFT 对象设置为更小的日期范围。

如果您需要使用 ggplot 来完成,请告诉我,我会编写代码。但通常情况下,我会尽可能使用包,因为它更干净!

Royr2 回答了这个问题,但是他已经几天没有将答案从评论中移到答案中,因此为了将答案捕获为标记答案,我只是将他的评论迁移到答案中。如果他发表他的答案,我会很乐意将他的答案标记为合适的答案。

我在这里为 plotly 的人们写了一些东西 -> http://moderndata.plot.ly/candlestick-charts-using-plotly-and-quantmod/ 使用 plot_ly() 而不是 ggplotly()。不用说,该函数的灵感来自 quantmod 包中的图表 :) 希望对您有所帮助... –

royr2 4 月 25 日在 5:02

@David Crook 这是一个简单的例子。

library(plotly)
library(quantmod)

prices <- getSymbols("MSFT", auto.assign = F)
prices <- prices[index(prices) >= "2016-01-01"]

# Make dataframe
prices <- data.frame(time = index(prices),
                     open = as.numeric(prices[,1]),
                     high = as.numeric(prices[,2]),
                     low = as.numeric(prices[,3]),
                     close = as.numeric(prices[,4]))

# Blank plot
p <- plot_ly()

# Add high / low as a line segment
# Add open close as a separate segment
for(i in 1:nrow(prices)){
  p <- add_trace(p, data = prices[i,], x = c(time, time), y = c(high, low), mode = "lines", evaluate = T,
                 showlegend = F,
                 marker = list(color = "grey"),
                 line = list(width = 1))

  p <- add_trace(p, data = prices[i,], x = c(time, time), y = c(open, close), mode = "lines", evaluate = T,
                 showlegend = F,
                 marker = list(color = "#ff5050"),
                 line = list(width = 5))
}

p

更新: 随着 plotly 4.0 的发布,这样做会容易得多:

library(plotly)
library(quantmod)

prices <- getSymbols("MSFT", auto.assign = F)
prices <- prices[index(prices) >= "2016-01-01"]

# Make dataframe
prices <- data.frame(time = index(prices),
                     open = as.numeric(prices[,1]),
                     high = as.numeric(prices[,2]),
                     low = as.numeric(prices[,3]),
                     close = as.numeric(prices[,4]))

plot_ly(prices, x = ~time, xend = ~time, showlegend = F) %>% 
  add_segments(y = ~low, yend = ~high, line = list(color = "gray")) %>% 
  add_segments(y = ~open, yend = ~close, 
               color = ~close > open,
               colors = c("#00b386","#ff6666"),
               line = list(width = 3))

有关更完整的示例,请参见此处:http://moderndata.plot.ly/candlestick-charts-using-plotly-and-quantmod/