如何将多条geom_smooth线添加到图例(ggplot)? [英] How to add multiple geom_smooth lines to the legend (ggplot)?

查看:113
本文介绍了如何将多条geom_smooth线添加到图例(ggplot)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a plot which includes multiple geom_smooth trendlines within one plot. My current code is as follows:

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()

将产生以下绘图:

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

The issue is I can't for the life of me include a simple legend where I can label what each trendline represents. The dataset is quite large- if it would be valuable in indentifying a solution I will post externally to Stackoverflow.

推荐答案

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

Your data is in the wide format, or like a matrix. There's no easy way to add a custom legend in ggplot, so you need to transform your current data to a long format. I simulated 3 curves like what you have, and you can see if you call geom_line or geom_smooth with a variable ("name" in the example below) that separates your different values, it will work and produce a legend nicely.

library(dplyr)
library(tidyr)
library(ggplot2)
X = 1:50
#simulate data
Data = data.frame(
       BA=X,
       BAgp1 = log(X)+rnorm(length(X),0,0.3),
       BAgp2 = log(X)+rnorm(length(X),0,0.3) + 0.5,
       BAgp3 = log(X)+rnorm(length(X),0,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)

这篇关于如何将多条geom_smooth线添加到图例(ggplot)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆