首页 > 解决方案 > 整个组的趋势线 - R

问题描述

我正在尝试为所有组绘制一条趋势线,但它为每个组绘制了一条趋势线。我使用的相同代码放在这里(使用 iris 数据集):

iris %>%
  mutate(id = as.numeric(rownames(iris))) %>%
  select(id, Sepal.Length, Sepal.Width, Petal.Length) %>%
  reshape(., direction = "long", varying = names(.)[2:4], v.names = "valor", idvar = c("id"), timevar = "tipo", times= colnames(.[2:4])) %>%
  ggplot(aes(x=id, y=valor, fill=tipo)) +
  geom_area() +
  geom_smooth(method = "lm")

我的数据框输出的图像(无线geom_smooth()

在此处输入图像描述

我尝试添加一条趋势线:

  geom_smooth(method = "lm")

但是它为每个组添加了一条趋势线,而我只需要一个作为总数。

标签: rggplot2trend

解决方案


aes为每个单独的几何设置映射:

iris %>%
  mutate(id = rownames(iris)) %>%
  select(id, Sepal.Length, Sepal.Width, Petal.Length) %>%
  reshape(., direction = "long", varying = names(.)[2:4], v.names = "valor", idvar = c("id"), timevar = "tipo", times= colnames(.[2:4])) %>%
  mutate(id = as.numeric(id)) %>%
  ggplot() +
  geom_area(aes(x=id, y=valor, fill=tipo)) +
  geom_smooth(aes(x=id, y=valor), method = "lm")

(我需要添加一个额外的 mutate 以更改id为 numeric 以使您的代码正常工作)


推荐阅读