Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何在时间序列的中途更改ggplot2中的线特性?_R_Ggplot2_Timeserieschart - Fatal编程技术网

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