【发布时间】:2015-12-29 20:06:45
【问题描述】:
在 ggplot2 中绘制股票数据时遇到问题,x 轴包含周末和节假日的间隙。 this 的帖子非常有帮助,但我在尝试使用有序因子时遇到了各种问题。
library(xts)
library(grid)
library(dplyr)
library(scales)
library(bdscale)
library(ggplot2)
library(quantmod)
getSymbols("SPY", from = Sys.Date() - 1460, to = Sys.Date(), adjust = TRUE, auto.assign = TRUE)
input <- data.frame(SPY["2015/"])
names(input) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
# i've tried changing rownames() to index(), and the plot looks good, but the x-axis is inaccurate
# i've also tried as.factor()
xaxis <- as.Date(rownames(input))
input$xaxis <- xaxis
p <- ggplot(input)
p <- p + geom_segment(aes(x = xaxis, xend = xaxis, y = Low, yend = High), size = 0.50) # body
p <- p + geom_segment(aes(x = xaxis - 0.4, xend = xaxis, y = Open, yend = Open), size = 0.90) # open
p <- p + geom_segment(aes(x = xaxis, xend = xaxis + 0.4, y = Close, yend = Close), size = 0.90) # close
p <- p + scale_y_continuous(scale_y_log10())
p + ggtitle("SPY: 2015")
上面的图(没有红色框)是用上面的代码段生成的。以下图表是尝试某些解决方案时的一些问题。首先,如果我尝试使用数据框的索引,我会生成漂亮的图形,但是 x 轴不准确;数据目前在 10 月结束,但在下图中,它在 7 月结束:
xaxis <- as.Date(index(input))
其次,如果我尝试将行名强制为有序因子,我会丢失水平刻度数据(代表开盘和收盘)。
xaxis <- factor(rownames(input), ordered = TRUE)
如果我使用包 bdscale,也会出现删除水平刻度的相同问题,但网格线更清晰:
p <- p + scale_x_bd(business.dates = xaxis)
【问题讨论】:
-
在您上面的问题中,“上图(无红框)”中产生的 X 轴有什么不准确之处?
-
红色框突出显示了我要移除的 x 轴间隙。我想要一个看起来像第二个图(没有间隙)的图,但是第一个图的 x 轴
-
那么,问题在于自动识别哪些日期是假期或周末,因为如果您这样做了,您可以将
input子集化为仅保留工作日,对吗? -
好吧,如果您检查数据,则该系列中没有周末或节假日。只是有差距。输入已经只保留工作日