R 如何在时间序列的中途更改ggplot2中的线特性?
从R 如何在时间序列的中途更改ggplot2中的线特性?,r,ggplot2,timeserieschart,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, Y2
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)
我想将21世纪所有点的线型
从“实线”改为“虚线”(可能还有线条大小
),即那些Y2K
等于真
的观测值
我做了一个groupby(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\u by
,并且过滤器步骤确保时间序列将在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")
另外,改变绘图宽度以去除尖峰伪影(红线)。您根本不需要映射到组。只需添加一个映射到linetype
的分组变量即可。您可能需要复制发生切换的点。由于dplyr
不符合我的口味,因此无法为您提供更多帮助。谢谢,但我接受@tonytonov的回答,因为它不会为线型创建单独的图例。如果您想删除线型图例,可以添加比例\u线型(guide=F)。
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))