在ggplot中将趋势线添加为其他图例

时间:2019-12-30 04:51:04

标签: r ggplot2

我有一个散点图,显示了一段时间内的连续数据。我的数据通过图例中表示的两个变量(类型和级别)来区分。我在数据中添加了一条趋势线,并希望将其作为单独的图例(除类型和级别之外)添加并标记为“趋势线”。我将不胜感激,以最有效的方式完成此工作。谢谢!

以下是可重现的示例:

library(tidyverse)

perc <- c(.5, .49, .67, .5, .67, .73, .82)
year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006)
type <- c(1, 1, 1, 1, 1, 2, 2)
type <- as.factor(type)
level <- c(3, 3, 3, 4, 4, 4, 4)
level <- as.factor(level)
data <- data.frame(year, perc, type, level)

ggplot(data, aes(x=year, y=perc, color = type, shape = level)) +
  geom_point(size = 3) +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE) +
  scale_color_manual(values = c("red", "black")) +
  scale_shape_manual(values = c(16, 17))

enter image description here

2 个答案:

答案 0 :(得分:2)

这样的帮助吗?

请注意我在geom_smooth下添加的新参数。

ggplot(data, aes(x=year, y=perc, group = type,
                 color = type, shape = level)) +
  geom_point(size = 3) +
  geom_smooth(se = FALSE, method = 'lm', 
              aes(group = 1, colour = "Trendline"),
              fullrange=TRUE, linetype=1) +
  scale_color_manual(values = c("red", "black", "blue")) +
  scale_shape_manual(values = c(16, 17, 18))

enter image description here

答案 1 :(得分:2)

这对我有用:

library(tidyverse)

perc <- c(.5, .49, .67, .5, .67, .73, .82)
year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006)
type <- c(1, 1, 1, 1, 1, 2, 2)
type <- as.factor(type)
level <- c(3, 3, 3, 4, 4, 4, 4)
level <- as.factor(level)
data <- data.frame(year, perc, type, level)

ggplot(data, aes(x=year, y=perc, color = type, shape = level, linetype = "Trendline")) +
  geom_point(size = 3) +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE) +
  scale_color_manual(values = c("red", "black")) +
  scale_shape_manual(values = c(16, 17)) +
  scale_linetype_discrete(name = "")

enter image description here