使用ggplot2在图例中添加趋势线

问题描述 投票:0回答:1

我想添加趋势线(蓝色虚线、黑色虚线和红色虚线),将时间序列点线图例分开。

year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006,
          2000, 2001, 2002, 2003, 2004, 2005, 2006,
          2000, 2001, 2002, 2003, 2004, 2005, 2006)

temp <- c(05, 08, 07, 05, 10, 13, 08, 
          10, 12, 11, 08, 14, 17, 10, 
          20, 18, 23, 25, 21, 28, 30)

type <- c("min","min","min","min","min","min","min",
          "mean","mean","mean","mean","mean","mean","mean",
          "max","max","max","max","max","max","max")

type <- as.factor(type)

series <- data.frame(year = year, temp = temp, type = type)


ggplot(series, aes(x = year, y = temp,  group = type)) + geom_line(aes(color = type)) + 
  geom_point(aes(color = type)) +
  geom_smooth(aes(group = type, color = type ), formula = 'y ~ x' , method=lm, se = F, linetype = "dashed", show.legend = T) + 
  scale_color_manual(values =  c("blue","black", "red") ) + 
  xlim(2000,2006) +
  labs(x = "Year", 
       y = TeX("Temperatura"),
       colour = "Legend")
r ggplot2
1个回答
0
投票

我只需在您的

scale_linetype_manual()
代码上添加
guides
然后
ggplot
即可获得您想要的输出

ggplot(series, aes(x = year, y = temp,  group = type)) + 
  geom_line(aes(color = type)) + 
  geom_point(aes(shape = type)) +
  geom_smooth(aes(group = type, color = type ), formula = 'y ~ x' , method=lm, se = F, linetype = "dashed", show.legend = T) + 
  scale_color_manual(values =  c("blue","black", "red") ) + 
  xlim(2000,2006) +
  labs(x = "Year", 
       y = latex2exp::TeX("Temperatura"),
       colour = "Legend") +
  scale_linetype_manual(values = c("dotdash","dotdash","dotdash"), name = "trendline", labels = c("max", "mean", "min")) +
  guides(linetype = guide_legend(override.aes = list(linetype = c("dotdash", "dotdash", "dotdash"),color = scales::hue_pal()(2))))

© www.soinside.com 2019 - 2024. All rights reserved.