David Crook David Crook - 3 months ago 39
R Question

BoxPlot in ggplotly

I'm trying to draw a time series boxplot in R with the plotly libraries, however I need to be able to have total control of the ymin, ymax, ylow etc.

It renders perfectly fine in ggplot2, althought with a ton of warnings. It fails to render in ggplotly

Here is what I have.

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")

Answer

@David Crook here's a simple example.

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

UPDATE: with the release of plotly 4.0 doing this is a lot easier:

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))

For a more complete example see here: http://moderndata.plot.ly/candlestick-charts-using-plotly-and-quantmod/

Comments