如何在时间序列中途改变ggplot2中的线属性?

时间:2015-04-15 12:49:31

标签: 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)

enter image description here

我想更改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点连接(如果数据是基于年份的,那么可能否则就是视觉上的不连续性。

2 个答案:

答案 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")

enter image description here

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))