如何只绘制几年时间序列中的特定月份?

时间:2018-06-23 09:17:27

标签: r ggplot2

我的数据框包含2002年至2017年6月,7月和8月的每日温度数据。

date          temperature
2002-06-01    9.882000
2002-06-02    9.698667
2002-06-03    12.941667
...
2017-08-29    13.271125
2017-08-30    16.332750
2017-08-31    20.986000

日期格式为POSIXct。我正在尝试创建一个只显示每年相关月份的图。我用以下代码尝试了ggplot2:

ggplot(NULL, aes(x = date, y = temperature)) +
   geom_line(data = tair_summer_night_mean, color = "blue") +
   xlab(label = "Time") +
   ylab(label = "Night time temperature in °C")

这导致:

enter image description here

有没有办法告诉ggplot不要显示我没有数据的空间?

1 个答案:

答案 0 :(得分:0)

这是camille的建议的后续行动。通过构面绘制数据可能是最简单的解决方案。您可以按照她的参考资料在数据中创建年份列,然后对其进行分组,也可以如下所示在gglot中计算分组变量。

library(ggplot2)
#
#  make some test data
#
  tair_summer_night_mean <- data.frame(date=c( seq.Date(as.Date("2002-06-01"), as.Date("2002-08-31"),1), 
                                        seq.Date(as.Date("2003-06-01"), as.Date("2003-08-31"),1), 
                                        seq.Date(as.Date("2004-06-01"), as.Date("2004-08-31"),1)))
  tair_summer_night_mean[,"temperature"] <-  runif(nrow(tair_summer_night_mean), min=9, max=21 )
#
#  make plots faceted by year
# 
  sp <-  ggplot(tair_summer_night_mean, aes(x = date, y = temperature)) +
         geom_line(color = "blue") + 
         xlab(label = "Time") +
         ylab(label = "Night time temperature in °C") +
         facet_wrap( ~ format(date, "%Y"), scales = "free_x")
   plot(sp)

显示图表

enter image description here

相关问题