ggplot2:从x轴日期删除周末和假日的空格

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

enter image description here

上面的图(无框红色框)是使用上面的代码段生成的.以下图表是尝试某些解决方案时的一些问题.首先,如果我尝试使用数据框的索引,我将生成一个漂亮的图形,但x轴是不准确的;该数据目前在10月份结束,但在下面的情节中,它将于7月结束:
enter image description here

xaxis <- as.Date(index(input))

其次,如果我尝试将rownames强制转换为有序因子,我会丢失水平刻度数据(表示打开和关闭).
enter image description here

xaxis <- factor(rownames(input), ordered = TRUE)

如果我使用包bdscale,则会发生删除水平刻度的相同问题,但网格线更清晰:

enter image description here

p <- p + scale_x_bd(business.dates = xaxis)
您可能需要将日期视为离散值而不是连续值.这种方法略微简化了代码版本,可能如下所示:

getSymbols("SPY", from = Sys.Date() - 1460, to = Sys.Date(), adjust = TRUE, auto.assign = TRUE)
SPY <- SPY["2015/"]
colnames(SPY) <- sub("SPY.","", colnames(SPY))
month_brks <- c(1,endpoints(SPY, "months")[-1])

p <- ggplot(data.frame(xaxis=seq(nrow(SPY)), SPY))
p <- p + geom_linerange(aes(x=xaxis, ymin=Low, ymax=High), size=.5)
p <- p + geom_text(aes(x = xaxis,  y = Open), size = 4., label="-", hjust=.7, vjust=0)  # Open
p <- p + geom_text(aes(x = xaxis,  y = Close), size = 4., label="-", hjust=-.1, vjust=0)  # close
p <- p + scale_x_continuous(breaks=month_brks, labels=format(index(SPY)[month_brks], "%d %b %Y"))
p <- p + labs(title="SPY: 2015", x="Date", y="Price")

UPDATE

更新轴标签的处理.

相关文章
相关标签/搜索