我试图在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")
答案 0 :(得分:1)
@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/
答案 1 :(得分:0)
您可以使用quantmod包执行此操作。
尝试以下方法:
library(quantmod)
getSymbols("MSFT")
candleChart(MSFT,multi.col=TRUE,theme='white')
如果不需要全部,可以将MSFT对象修剪为较小的日期范围。
如果您需要使用ggplot,请告诉我,我会写下代码。但通常情况下,我会尽可能地使用包装,因为它更干净!
答案 2 :(得分:0)
Royr2回答了这个问题,但他几天之内没有将评论的答案转移到答案中,所以为了将答案作为一个明确的答案,我只是将他的评论转移到答案中。如果他发布了答案,我很乐意将他的答案标记为适当的答案。
&#34;
我在这里为人们写了一些东西 - &gt; http://moderndata.plot.ly/candlestick-charts-using-plotly-and-quantmod/使用plot_ly()而不是ggplotly()。不言而喻,该功能受到quantmod包中图表的启发:)希望有帮助...... -
&#34;
royr2 4月25日5:02