带有日期轴R的ggplot垂直线

时间:2015-05-18 12:55:14

标签: r ggplot2 time-series vline

我在R中用ggplot绘制垂直线时遇到了问题。

我希望每个星期天在我的时间系列上画一条垂直线:

VisitDate VisitMonth VisitYear      City   Weekday VisitWeek Code_CxF               Centre  Location
1 2014-05-02           05        2014 Barcelona    05Friday  2014-04-28  CxF_BCN CaixaForum Barcelona Catalunya
2 2014-05-03           05        2014 Barcelona  06Saturday  2014-04-28  CxF_BCN CaixaForum Barcelona Catalunya
3 2014-05-04           05        2014 Barcelona    07Sunday  2014-04-28  CxF_BCN CaixaForum Barcelona Catalunya
4 2014-05-06           05        2014 Barcelona   02Tuesday  2014-05-05  CxF_BCN CaixaForum Barcelona Catalunya
5 2014-05-07           05        2014 Barcelona 03Wednesday  2014-05-05  CxF_BCN CaixaForum Barcelona Catalunya
6 2014-05-08           05        2014 Barcelona  04Thursday  2014-05-05  CxF_BCN CaixaForum Barcelona Catalunya

我尝试过以下表达式:

ggplot(data = MUSEUS_PLOT, aes(x = VisitDate, y = Visitors.x)) + 
  geom_line(size=0.25, aes(x = VisitDate, y = Visitors.x, colour = "CxF")) + 
  geom_line(aes(y = Visitors.y, colour = "MNAC")) + 
  labs(title = "MONTJUICH May 2014", x = "Day", y = "Visitors") +
  scale_colour_manual(name="Legend",values=c(CxF="darkcyan", MNAC="darkorange2")) +
  geom_vline(aes(xintercept = which(weekdays(MUSEUS_PLOT$VisitDate) == "Sunday")))

但它不起作用:

Error in data.frame(xintercept = c(3L, 9L, 15L, 21L), PANEL = c(1L, 1L,  : 
  arguments imply differing number of rows: 4, 26

一些想法?

1 个答案:

答案 0 :(得分:1)

使用星期日数据创建一个新数据表:

MUSEUS_PLOT_SUNDAYS <- MUSEUS_PLOT[weekdays(MUSEUS_PLOT$VisitDate) == "Sunday"]

并为此更改geom_vline:

  geom_vline(data = MUSEUS_PLOT_SUNDAYS,aes(xintercept = as.numeric(VisitDate)),colour = "black")