在 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")
The plot above (sans red boxes) is generated with the above code segment. And the following charts are some of the issues when attempting some solutions. First, if I try using the data frame's index, I will generate I nice looking graph, but the x-axis is inaccurate; the data currently ends in October, but in the plot below it ends in July:
xaxis <- as.Date(index(input))
Second, if I try coercing the rownames to an ordered factor, I lose my horizontal tick data (representing the open and the close).
xaxis <- factor(rownames(input), ordered = TRUE)
如果我使用 bdscale 包,也会出现删除水平刻度的相同问题,但网格线更清晰:
p <- p + scale_x_bd(business.dates = xaxis)