绘制时间序列ggplot月 - 年,xaxis只显示月值?

时间:2016-03-22 17:14:49

标签: r date plot ggplot2 time-series

我有8年的时间序列数据。我可以绘制我的数据,但我希望x轴只显示我有数据的月份。

my figure

我的问题是我的x轴显示1月,但我的数据仅适用于每年的6月,7月和8月。

我还想在每年添加垂直线以分开..

以下是我的脚本到目前为止的样子:

ggplot(data=CMRB, aes(x=D, y=Densite, group = habitat)) + geom_line() + scale_x_date(date_labels ="%b%Y")+ geom_point( aes(shape=habitat),size=4, fill="white")

我的数据如下:

  Annee Grille Periode   Densite        SE Methode espece notes notes_2
82  2004    LG1     PP2 1.8888330 0.3990163    secr   brun            NA
83  2004    LG1     PP3 3.8880450 0.7570719    secr   brun            NA
84  2004    LG1     PP4 3.3281370 0.5573953    secr   brun            NA
85  2005    LG1     PP1 0.2367488        NA    secr   brun  mnka      NA
86  2005    LG1     PP2 0.4791649 0.2105729    secr   brun            NA
87  2005    LG1     PP3 0.1597214 0.1302571    secr   brun            NA
   habitat Mois      Date          D
82   humid   07 07/1/2004 2004-07-01
83   humid   08 08/1/2004 2004-08-01
84   humid   08 08/1/2004 2004-08-01
85   humid   06 06/1/2005 2005-06-01
86   humid   07 07/1/2005 2005-07-01
87   humid   08 08/1/2005 2005-08-01
> 

D是我创建的用于将日期(字符)转换为日期格式的列。

有人知道怎么做吗?如果可能的话,我还希望没有数据的月份可以减少图表中的空间,留出更多的空间来查看从6月到8月的数据......

干杯

尼科

1 个答案:

答案 0 :(得分:1)

这应该转换为日期列。

CMRB <- as.Date(CMRB$D, format = "%Y-%m-%d")

如果您想绘制时间序列数据,建议您使用dygraphs

例如,

library(dygraphs)

library(xts)

ts_object <- as.xts(CMRB$Densite, CMRB$D)

dygraph(ts_object)

这是引导您完成dygraphs的网站的圣杯。

https://rstudio.github.io/dygraphs/