首页 > 解决方案 > 在绘图上隐藏缺失的日期

问题描述

我正在尝试绘制来自 3 个不同年份(2016-7-8)的数据,但我只有夏季月份(基本上没有从 9 月到 4 月的数据)。

当我绘制数据时,没有数据的月份出现在图表上,留下大而难看的空白

当我传递因子中的日期时,这些空格就会消失。但随后日期不再出现在 x 轴上,我只得到数字......

这是我的一些数据:

date    MD g/day    AM g/day
26/04/2016  82  154
27/04/2016  238 140
28/04/2016  140 661
29/04/2016  181 304
30/04/2016  92  329
07/07/2017  976 126
08/07/2017  923 47
09/07/2017  527 77
10/07/2017  285 84
11/07/2017  8704    155
07/06/2018  3115    170
08/06/2018  151 65
09/06/2018  415 247
10/06/2018  153 402
11/06/2018  172 95
12/06/2018  188 114

我将我的数据转换为以 MD 和 AM 作为因子水平

a <- loads$MD.g.day
b <- loads$AM.g.day
d <- data.frame(date=loads$date, MD=a, AM=b)
d$date <- as.Date(loads$date, format='%d/%m/%Y')
colnames(d) <- c('date','MD','AM')
e <- rbind(data.frame(date=c(d$date), gday=c(d$MD), factor='MD'),
           data.frame(date=c(d$date), gday=c(d$AM), factor='AM'))

然后我使用:

p <- ggplot(data=e,aes(x=date))+ #select data
  geom_point(aes(y=gday*7/35, color=factor, shape=factor), data=e[e$factor=='MD', ], )+ #select and scale
  geom_line(aes(y=gday*7/35, color=factor), data=e[e$factor=='MD', ])+ #select and scale md

  geom_point(aes(y=gday, color=factor, shape=factor), data=e[e$factor=='AM', ])+ #select other compound
  geom_line(aes(y=gday, color=factor), data=e[e$factor=='AM', ])+ #select other compound


  scale_y_continuous(name = 'AM [g/day]\n',
                     sec.axis = sec_axis(~.*35/7, name = "MD [g/day]\n"), limits = c(0,7000))+  #add y-axis texts and secondary y-axis
  scale_x_date(date_labels = '%e %b %y', date_breaks='1 month')+  #arrange text for the x-axis
  scale_color_manual(values=c(MD='magenta', AM='light green'))+ #define colors
  scale_shape_manual(values=c(MD=21, AM=21))+ #define dot shapes
  scale_size_manual(values=c(MD=1.5, AM=2.5))+ #define dot sizes
  theme(axis.text.x = element_text(angle=90)), #turn text from the x-axis

标签: rggplot2

解决方案


您的代码应该可以正常工作,只需稍作改动并添加facet_wrap. scale_x_date只需设置date_breaks为而"1 day"不是"1 month",然后调用:

library(lubridate) # Needed for `year` function.
p + facet_wrap(~year(date), scales = "free_x")

上面的代码返回以下图:

在此处输入图像描述


推荐阅读