Tem*_*Rex 5 r ggplot2 timeserieschart
从economics{ggplot2}数据集中获取以下两个时间序列的简单图表
require(dplyr)
require(ggplot2)
require(lubridate)
require(tidyr)
economics %>%
gather(indicator, percentage, c(4:5), -c(1:3, 6)) %>%
mutate(Y2K = year(date) >= 2000) %>%
group_by(indicator, Y2K) %>%
ggplot(aes(date, percentage, group = indicator, colour = indicator)) + geom_line(size=1)
Run Code Online (Sandbox Code Playgroud)

我想将21世纪所有点的linetype"固体"改为"虚线"(也可能是线size),即对于那些Y2K等于的观察TRUE.
我做了一个group_by(indicator, Y2K)但是在ggplot命令里面看来我不能group =在多个级别上使用,所以行属性indicator现在只有不同.
问题:如何实现这种分段线条外观?
更新:我的首选解决方案是@sahoang的轻微调整:
economics %>%
gather(indicator, percentage, c(4:5), -c(1:3, 6)) %>%
ggplot(aes(date, percentage, colour = indicator)) +
geom_line(size=1, aes(linetype = year(date) >= 2000)) +
scale_linetype(guide = F)
Run Code Online (Sandbox Code Playgroud)
这消除了group_by@Roland所评论的,并且filter步骤确保时间序列将在Y2K点处连接(如果数据是基于年份的,则可能存在视觉上的不连续性).
比@Roland的建议更容易:
economics %>%
gather(indicator, percentage, c(4:5), -c(1:3, 6)) %>%
mutate(Y2K = year(date) >= 2000) %>%
group_by(indicator, Y2K) -> econ
ggplot(econ, aes(date, percentage, group = indicator, colour = indicator)) +
geom_line(data = filter(econ, !Y2K), size=1, linetype = "solid") +
geom_line(data = filter(econ, Y2K), size=1, linetype = "dashed")
Run Code Online (Sandbox Code Playgroud)

PS更改绘图宽度以消除尖峰伪影(红线).
| 归档时间: |
|
| 查看次数: |
1176 次 |
| 最近记录: |