添加第二个x轴标签或更改标签到日期

时间:2014-08-25 16:53:00

标签: r date ggplot2 histogram axis-labels

之前我问了一个关于制作日期数据直方图的问题here 答案很有效。现在我正在尝试添加第二组x轴标签,包括年和月(1/3月,1/10月)或仅用日/月替换年。

前20个条目是

Index   Sex LostMate    DayofYear   Nested  DateLost    DOTYMarch1  DOTYLost    YLost       DOTYAfterMarch31Lost    Seasons
22  F   5/1/1994    62  N   5/1/1994    60  121 1994    61  Spring
2   M   5/20/1988   81  N   5/20/1988   61  141 1988    80  Spring
4   M   9/6/1997    190 Y   9/6/1997    60  249 1997    189 Fall
21  F   9/13/1997   197 Y   9/13/1997   60  256 1997    196 Fall
7   M   9/15/1997   199 Y   9/15/1997   60  258 1997    198 Fall
13  F   9/16/1988   200 Y   9/16/1988   61  260 1988    199 Fall
20  F   9/23/1996   207 Y   9/23/1996   61  267 1996    206 Fall
5   M   9/24/1996   208 N   9/24/1996   61  268 1996    207 Fall
6   M   9/27/1996   211 N   9/27/1996   61  271 1996    210 Fall
17  F   10/9/1999   223 N   10/9/1999   60  282 1999    222 Fall
18  F   10/20/1990  234 N   10/20/1990  60  293 1990    233 Fall
19  F   10/25/2001  239 N   10/25/2001  60  298 2001    238 Fall
12  F   10/26/1986  240 N   10/26/1986  60  299 1986    239 Fall
14  F   12/30/1986  305 N   12/30/1986  60  364 1986    304 Winter
16  F   1/7/1992    312 N   1/7/1992    61  7   1991    312 Winter
9   F   1/12/1985   318 Y   1/12/1985   60  12  1984    317 Winter
11  F   1/13/1985   319 Y   1/13/1985   60  13  1984    318 Winter
8   F   1/18/1989   324 Y   1/18/1989   60  18  1988    323 Winter
15  F   1/19/1991   325 N   1/19/1991   60  19  1990    324 Winter
3   M   1/31/1985   337 N   1/31/1985   60  31  1984    336 Winter

我在这一点上使用的代码是

goose$DateLost <- as.POSIXct(goose$LostMate,
      format = "%m/%d/%Y", tz = "GMT")

goose$Sex2<-factor(goose$Sex, levels=c("F","M"))
levels(goose$Sex2) <- c("Females", "Males") 

p3 <- ggplot(goose, 
         aes(x=DOTYAfterMarch31Lost,fill=Nested,xmin=0,))+ 
  scale_fill_manual(values = c("grey","black")
                , labels = c("N" = "No", "Y" = "Yes"))+
  scale_linetype_manual(values=c(1,3)) +
labs(x = "Day of year (from 1 March)",
   y = "Mate lost",
   title = "Timing of goose mate deaths")+
theme_bw() +
theme(
plot.background = element_blank()
,panel.grid.major = element_blank()
,panel.grid.minor = element_blank()
,panel.border = element_blank()
) +
theme(axis.line = element_line(color = 'black'))+
stat_bin(binwidth=1,position="identity")+
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0),breaks=c())

print(p3)

p3 + facet_grid(Sex2 ~ .)

我查看了其他帖子,例如herehere,但无法获得我想要的内容。任何想法将不胜感激。提前谢谢!

1 个答案:

答案 0 :(得分:2)

这个怎么样?首先,定义标签

labelat <- seq(as.Date("2000-03-01"), as.Date("2001-03-01"), by="1 month")
labels <- strftime(labelat, "%b %d")
labelat <- labelat-labelat[1]

然后在scale_x_continuous

中使用它们
...
scale_x_continuous(expand = c(0, 0), breaks=as.numeric(labelat), labels=labels) +
...

给出了

enter image description here