【问题标题】:How to change line properties in ggplot2 halfway in a time series?如何在时间序列中途更改 ggplot2 中的线属性?
【发布时间】:2015-04-15 12:49:31
【问题描述】:

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 等于 @987654327 的观察@。

我执行了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_byfilter 步骤确保时间序列将在 Y2K 点连接(如果数据基于年份,则可能存在视觉不连续性否则)。

【问题讨论】:

  • 您根本不需要映射到group。您只需要一个 linetype 映射到的附加分组变量。可能您需要复制发生切换的点。无法为您提供更多帮助,因为 dplyr 不合我的口味。

标签: r ggplot2 timeserieschart


【解决方案1】:

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

附:改变绘图宽度以消除尖峰伪影(红线)。

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

    • 谢谢,但我接受@tonytonov 的回答,因为它不会为线型创建单独的图例。
    • 如果你想去掉线型图例,你可以添加 scale_linetype(guide = F)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2020-04-10
    相关资源
    最近更新 更多