我想在此图中添加其他数据点

时间:2015-03-12 14:29:48

标签: r ggplot2

我有这些数据:

 d <- data.frame(date=as.Date(c("1971-09-01", "1991-12-01", "1994-12-01",       
                                "2000-01-01", "2002-08-01", "2005-08-01")), 
                 event=c("birth", "entered college", "BS", 
                         "entered grad school", "MS", "PhD"), 
                 big_events=c(" ", "first bf", "married", 
                              " ", " ", "kids"))

 ggplot() +
   scale_x_date(limits=as.Date(c("1970-1-1", "2010-12-31"))) +
   scale_y_continuous(name="", breaks=NULL, limits=c(0,1)) +
   geom_vline(data=d, mapping=aes(xintercept=as.numeric(date)),    
   color="blue") +
   geom_text(data=d, mapping=aes(x=date, y=0, label=event), size=4,     
   angle=90, vjust=-0.4, hjust=0)

上面的“ggplot”部分将“事件”随着时间的推移绘制成垂直条,这是我想要的,但我无法弄清楚如何在同一个图中随时间添加点。

2 个答案:

答案 0 :(得分:1)

添加geom_point

d <- data.frame(date=as.Date(c("1971-09-01", "1991-12-01", "1994-12-01", 
                               "2000-01-01", "2002-08-01", "2005-08-01")), 
                event=c("birth", "entered college", "BS", 
                        "entered grad school", "MS",  "PhD"), 
                big_events=c(" ", "first bf", "married", " ", 
                             " ", "kids"))
# Some random dates and heights on the y-axis
b <- data.frame(date=as.Date(c("1972-09-01", "1992-12-01", "1992-12-01", 
                               "2004-01-01", "2003-08-01", "2002-08-01")),
                height=c(0.6, 0.8, 0.3, 0.2, 0.1, 0.4))

ggplot() +
  scale_x_date(limits=as.Date(c("1970-1-1", "2010-12-31"))) +
  scale_y_continuous(name="", breaks=NULL, limits=c(0,1)) +
  geom_vline(data=d, mapping=aes(xintercept=as.numeric(date)),    
             color="blue") +
  geom_text(data=d, mapping=aes(x=date, y=0, label=event), size=4,     
            angle=90, vjust=-0.4, hjust=0) + 
  # Add this line with your new data and specify the x,y data
  geom_point(data=b, aes(x=date, y=height))

它产生了这个: data

答案 1 :(得分:0)

您已将y范围定义为0-1。只需在y轴上添加您想要指向数据的点并添加geom_point即可。鉴于您只想在重大事件中使用点,这样做:

d=data.frame(date=as.Date(c("1971-09-01", "1991-12-01", "1994-12-01",       
                            "2000-01-01", "2002-08-01", "2005-08-01")), 

             event=c("birth", "entered college", "BS", "entered grad school", "MS",    
                     "PhD"), 

big_events=c(" ", "first bf", "married", " ", " ",    
             "kids"),
y_dot = .5)


ggplot() +
  scale_x_date(limits=as.Date(c("1970-1-1", "2010-12-31"))) +
  scale_y_continuous(name="", breaks=NULL, limits=c(0,1)) +
geom_vline(data=d, mapping=aes(xintercept=as.numeric(date)),    
            color="blue") +
geom_text(data=d, mapping=aes(x=date, y=0, label=event), size=4,     
          angle=90, vjust=-0.4, hjust=0) +
geom_point(data = d[d$big_events != ' ', ], aes(y = y_dot, x = date))