5

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 世纪所有点的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)

这消除了group_by@Roland 所评论的,这些filter步骤确保时间序列将在 Y2K 点连接(如果数据是基于年份的,否则可能会出现视觉上的不连续性)。

4

2 回答 2

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

在此处输入图像描述

PS 改变绘图宽度以去除尖峰伪影(红线)。

于 2015-04-15T13:25:01.030 回答
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))
于 2015-04-15T13:32:14.350 回答