如何在时间序列中途更改ggplot2中的线属性? [英] How to change line properties in ggplot2 halfway in a time series?

查看:70
本文介绍了如何在时间序列中途更改ggplot2中的线属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经济学{ggplot2} 数据集中获取以下两个时间序列的直观图

Take the following straightforward plot of two time series from the economics{ggplot2} dataset

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 从"solid"更改为"dashed"(可能还有 size 线),即那些 Y2K 等于 TRUE 的观测值.

I would like to change the linetype from "solid" to "dashed" (and possibly also the line size) for all points in the 21st century, i.e. for those observations for which Y2K equals TRUE.

我做了 group_by(indicator,Y2K),但是在 ggplot 命令中,看来我不能在多个级别上使用 group = 线属性现在仅在 indicator 上有所不同.

I did a group_by(indicator, Y2K) but inside the ggplot command it appears I cannot use group = on multiple levels, so the line properties only differ by indicator now.

问题:如何获得这种分段的线条外观?

Question: How can I achieve this segmented line appearance?

更新:我的首选解决方案是@sahoang提出的解决方案:

UPDATE: my preferred solution is a slight tweak from the one by @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点(以防数据以年份为基础,否则可能会出现视觉不连续).

This eliminates the group_by as commented by @Roland, and the filter steps make sure that the time series will be connected at the Y2K point (in case the data would be year based, there could be a visual discontinuity otherwise).

推荐答案

比@Roland的建议还容易:

Even easier than @Roland's suggestion:

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.更改绘图宽度以消除尖峰伪影(红线).

P.S. Alter plot width to remove spike artifacts (red line).

这篇关于如何在时间序列中途更改ggplot2中的线属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆