r - 在绘图上隐藏缺失的日期
问题描述
我正在尝试绘制来自 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
解决方案
推荐阅读
- java - Java 应用程序启动突然异常缓慢
- reactjs - 在 setState(气泡运动)之后,Highchart 未更新
- java - 如何理解 Java Timer `scheduleAtFixedRate` 方法的`catch up` 和 `schedule` 方法的实际运行时间?
- java - 在 Serializable 类的构造函数中定义对象
- appium - driver.navigate.back() 在 iOS v12 中不起作用
- bash - 如何从字符串评估日期
- python-3.x - 在 python 3 中更改硬编码值
- python - 字典未根据完整字典更新,但仅更新最终元素
- html - 如何垂直居中左侧的徽标和标题右侧的导航?
- python - Flask Sqlalchemy 比较两个相关表的两个日期