如何将多个geom_smooth线添加到图例(ggplot)?

我正在尝试创建一个在一个图中包含多个geom_smooth趋势线的图。我当前的代码如下:

png(filename="D:/Users/...",width = 10,height = 8,units = 'in',res = 300)
ggplot(Data) + 
  geom_smooth(aes(BA,BAgp1),colour="red",fill="red") + 
  geom_smooth(aes(BA,BAgp2),colour="turquoise",fill="turquoise") + 
  geom_smooth(aes(BA,BAgp3),colour="orange",fill="orange") + 
  xlab(bquote('Tree Basal Area ('~cm^2~')')) + 
  ylab(bquote('Predicted Basal Area Growth ('~cm^2~')')) + 
  labs(title = expression(paste("Other Softwoods")),subtitle = "Tree Level Basal Area Growth") +
  theme_bw()
dev.off()

这将产生以下情节:

如何将多个geom_smooth线添加到图例(ggplot)?

问题是我无法为自己提供一个简单的图例,可以在其中标注每个趋势线所代表的含义。数据集非常大-如果它对于确定我将在外部发布到Stackoverflow的解决方案很有用。

gehui19890302 回答:如何将多个geom_smooth线添加到图例(ggplot)?

您的数据采用宽格式或矩阵形式。在ggplot中添加自定义图例并不容易,因此您需要将当前数据转换为长格式。我模拟了类似的3条曲线,可以看到是否使用一个变量(在下面的示例中为“ name”)分隔不同的值来调用geom_line或geom_smooth,它将很好地工作并产生图例。

library(dplyr)
library(tidyr)
library(ggplot2)
X = 1:50
#simulate data
Data = data.frame(
       BA=X,BAgp1 = log(X)+rnorm(length(X),0.3),BAgp2 = log(X)+rnorm(length(X),0.3) + 0.5,BAgp3 = log(X)+rnorm(length(X),0.3) + 1)

# convert this to long format,use BA as id
Data <- Data %>% pivot_longer(-BA)
#define colors
COLS = c("red","turquoise","orange")
names(COLS) = c("BAgp1","BAgp2","BAgp3")
###
ggplot(Data) + 
  geom_smooth(aes(BA,value,colour=name,fill=name)) +
  # change name of legend here 
  scale_fill_manual(name="group",values=COLS)+
  scale_color_manual(name="group",values=COLS)

enter image description here

本文链接:https://www.f2er.com/3170008.html

大家都在问