从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)
我想更改linetype
来自" solid" to" dashed" (对于21世纪所有点,也可能是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)
这消除了@Roland评论的group_by
,并且filter
步骤确保时间序列将在Y2K点连接(如果数据是基于年份的,那么可能否则就是视觉上的不连续性。
答案 0 :(得分:5)
比@ 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")
P.S。改变绘图宽度以消除尖峰伪影(红线)。
答案 1 :(得分:4)
require(dplyr)
require(ggplot2)
require(lubridate)
require(tidyr)
economics %>%
gather(indicator, percentage, c(4:5), -c(1:3, 6)) %>%
mutate(Y2K = year(date) >= 2000) %>%
ggplot(aes(date, percentage, colour = indicator)) +
geom_line(size=1, aes(linetype = Y2K))