Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.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 - Fatal编程技术网

R 使用数据子集向ggplot2中的时间序列图添加线性趋势线

R 使用数据子集向ggplot2中的时间序列图添加线性趋势线,r,ggplot2,R,Ggplot2,我正在根据不同行业公司的净销售额数据研究这一流行病。为此,我有一个包含不同行业公司净销售额数据的数据集。现在,我想在一张图上绘制每个行业的图,其中一条线对应于每年的总净销售额(2010-2020年),另一条是2010-2019年至2020年的趋势线(因此,考虑到前几年,2020年的预期净销售额)。通过这种方式,我可以看到2020年是否出现了明显更糟糕的数字。 我使用dplyr对第一批图表(每个行业每年的总净销售额)进行了排序,其中包括: library(ggplot); library(tidy

我正在根据不同行业公司的净销售额数据研究这一流行病。为此,我有一个包含不同行业公司净销售额数据的数据集。现在,我想在一张图上绘制每个行业的图,其中一条线对应于每年的总净销售额(2010-2020年),另一条是2010-2019年至2020年的趋势线(因此,考虑到前几年,2020年的预期净销售额)。通过这种方式,我可以看到2020年是否出现了明显更糟糕的数字。 我使用
dplyr
对第一批图表(每个行业每年的总净销售额)进行了排序,其中包括:

library(ggplot); library(tidyverse)
Industries <- df %>%
      group_by(NAICS, Year) %>%
      summarize(Sales = mean(`Net Sales`))
    
Industry_Plot <- ggplot(data = Industries, aes(Year, Sales)) +
  theme_bw() +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank()) +
  geom_line(color = "steelblue", size = 1)
库(ggplot);图书馆(tidyverse)
行业%
组别(NAICS,年份)%>%
汇总(销售额=平均值(“净销售额”)

Industry_Plot我相信您希望使用geom_smooth(method='lm'…)和子集参数,例如:

ggplot(data = Industries, aes(Year, Sales)) +
  theme_bw() +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank()) +
  geom_line(color = "steelblue", size = 1)  +
 geom_smooth(method='lm', formula= y~x, color='red', se=FALSE) + 
 geom_smooth(data=subset(Industries, Year < 2020), method='lm', formula= y~x, color='green', se=FALSE)  
 
ggplot(数据=行业、不良事件(年份、销售额))+
主题_bw()+
主题(axis.text.y=element_blank(),
axis.ticks.y=元素_blank(),
panel.grid=element\u blank()+
几何尺寸线(颜色=“钢蓝”,尺寸=1)+
geom_平滑(方法=lm',公式=y~x,颜色=red',se=FALSE)+
geom_smooth(数据=子集(行业,2020年以前),方法=lm',公式=y~x,颜色=green',se=FALSE)

@dww请注意,OP希望在同一图表中有两条趋势线:一条用于2010-2020年。还有一个是2010-2019年,所以问题不同于
ggplot(data = Industries, aes(Year, Sales)) +
  theme_bw() +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank()) +
  geom_line(color = "steelblue", size = 1)  +
 geom_smooth(method='lm', formula= y~x, color='red', se=FALSE) + 
 geom_smooth(data=subset(Industries, Year < 2020), method='lm', formula= y~x, color='green', se=FALSE)