将geom_vline与facet_wrap一起使用

时间:2015-04-27 22:49:05

标签: r ggplot2

我使用以下代码在其中有一个带有facets的线图:

vLines <- data.frame('Date'=as.Date('2014/1/1'))

p <- ggplot(toPlot[1:296,], aes( Date, value)) + theme_bw() +ylab('Transactions') + xlab('') +
  scale_x_date(breaks=x_breaks, labels=x_labels)
p <- p + geom_line(aes(colour = variable, fill= variable),size=1.5) +
  theme(axis.text.y=element_text(hjust=0, angle=0), 
        axis.text.x = element_text(hjust=1, angle=45),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x=element_line(color='grey90',linetype='dashed'),
        panel.grid.major.y=element_line(color='grey90',linetype='dashed'),
        plot.title=element_text(size=20),
        axis.text=element_text(size=10),
        legend.text=element_blank(),
        legend.key=element_blank(),
        legend.title=element_blank(),
        legend.position="none") +
  scale_y_continuous(label=thousand_formatter) +
  ggtitle('Title')+
  scale_fill_manual(values=c("#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6")) +
  facet_wrap(~OrderType,nrow=3,scales="free") +
  geom_vline(data=vLines,aes(xintercept=Date))
p

请注意,我只想在每个面上绘制一条垂直线,我想在每个面上绘制多条垂直线。

dput(head(toPlot))的输出是:

structure(list(Date = structure(c(14853, 14914, 15034, 15187, 
15309, 15340), class = "Date"), OrderType = structure(c(1L, 1L, 
1L, 1L, 1L, 1L), .Label = c("Delivery", "eFiling", "Filing", 
"ProcessServing", "Research"), class = "factor"), variable = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("Orders", "Revenue"), class = "factor"), 
    value = c(1, 1, 1, 1, 18, 37)), .Names = c("Date", "OrderType", 
"variable", "value"), row.names = c(NA, 6L), class = "data.frame")

当我尝试执行上述代码时,出现以下错误:

Error: Discrete value supplied to continuous scale

任何有关解决此问题的建议都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

geom_vline位更改为:

geom_vline(xintercept=as.numeric(vLines$Date))