简体   繁体   English

如何为 lm (ggplot2) 中的 stat_smooth 创建置信区间和最佳拟合线的图例

[英]How can I create a legend for confidence interval and line of best fit for a stat_smooth in a lm (ggplot2)

Hi I have a great regression graph with 95% confidence interval and best fit line, however cant seem to add a legend, I've tried aes, scale_colour_manual, in various locations but to no avail.嗨,我有一个很棒的回归图,具有 95% 的置信区间和最佳拟合线,但是似乎无法添加图例,我已经在各个位置尝试了 aes、scale_colour_manual,但都无济于事。 My code so far is到目前为止我的代码是

ggplot(bats, aes(x=Days, y=AI))+geom_point(size=2, alpha=0.5) +
  xlab("Number of survey days") +
  ylab("Bat Activity Index")+
  stat_smooth( method = "lm",  formula = y~x,
    size = 1, col = "red", level = 0.95, alpha=0.5)+
  theme_light() +
  ggtitle("Regression test between Bat Activity Index and number of survey days")

到目前为止的图表

I should like a legend to show confidence intervals (shaded area) and line of best fit (red).我想要一个图例来显示置信区间(阴影区域)和最佳拟合线(红色)。

thanks in advance!提前致谢!

In ggplot2 , the way to create a legend is to specify your aesthetics within aes() .ggplot2 ,创建图例的方法是在aes()指定您的美学。 In this case, you have two separate aesthetics that you need to label: color should include one value that is labeled as "Line of Best Fit", and fill includes one value that is labeled as "Confidence Interval".在这种情况下,您需要标记两种不同的美学: color应包含一个标记为“最佳拟合线”的值, fill包含一个标记为“置信区间”的值。

You don't have a column in your dataset to apply to these two aesthetics, but if you input a character string into aes(color=..., fill=...) , then the character string will be used as the label and the aesthetics will be created for you.您的数据集中没有一列适用于这两种美学,但是如果您在aes(color=..., fill=...)输入字符串,则该字符串将用作标签美学将为您创造。 Observe how this works below when I use a made-up dataset that matches your own formatting.当我使用与您自己的格式匹配的虚构数据集时,请观察下面的工作原理。 Note in particular that col="red" is removed from the original code.特别注意col="red"已从原始代码中删除。 If it was not removed, it would overwrite the color= we placed inside aes() .如果它没有被删除,它将覆盖我们放置在aes()color=

library(ggplot2)

set.seed(1234)
bats <- data.frame(
  Days=sample(1:30, 200, replace=TRUE),
  AI=rnorm(200, mean=50, sd=20)
)

p <- 
  ggplot(bats, aes(x=Days, y=AI))+geom_point(size=2, alpha=0.5) +
  xlab("Number of survey days") +
  ylab("Bat Activity Index")+
  stat_smooth(
    aes(color="Line of Best Fit", fill="Confidence Interval"),
    method = "lm",  formula = y~x, size = 1,
    level = 0.95, alpha=0.5
  )+
  theme_light() +
  ggtitle("Regression test between Bat Activity Index and number of survey days") 
p

在此处输入图片说明

Well, now we have the legends, but likely this does not look like intended.好吧,现在我们有了传说,但这可能看起来不像预期的那样。 The legend for color has a red line and a gray background, whereas the one for fill has a red background and a blue line!颜色图例有一条红线和一条灰色背景,而填充图则有一条红线和一条蓝线! This is because ggplot2 is recognizing that "Line of Best Fit" and "Confidence Interval" are not the same string, so therefore creates different aesthetic values for both.这是因为ggplot2认识到"Line of Best Fit""Confidence Interval"不是同一个字符串,因此为两者创造了不同的审美价值。 In any case, you will want to specify the correct color and fill value.在任何情况下,您都需要指定正确的colorfill值。

Specifying Colors: If you specify fill= and color= in geom_smooth() , it will overwrite the one we made in aes() and you will remove the legend.指定颜色:如果您在geom_smooth()指定fill=color= ,它将覆盖我们在aes()geom_smooth() color= ,您将删除图例。 Therefore, we will specify the value using scale_color_manual() and scale_fill_manual() .因此,我们将使用scale_color_manual()scale_fill_manual()指定值。 We also do not want titles for the legends, so can remove it there too.我们也不想要图例的标题,因此也可以将其删除。

Changing the Appearance of the Key Glyphs: You also want to change the way the legends look.更改关键字形的外观:您还想更改图例的外观。 For "Line of Best Fit", you want to remove the fill from that legend icon (called a "key glyph").对于“最佳拟合线”,您希望从该图例图标(称为“关键字形”)中删除填充。 For "Confidence Interval", we want to remove the line and just show the gray box.对于“置信区间”,我们要删除该行并仅显示灰色框。 We can do all that using guides() and the override.aes= argument within guide_legend() .我们可以使用guides()guide_legend()override.aes=参数来完成所有这些。

Position of Legends: Finally, We want to move the legend to the bottom for a better overall look, which is accessed via the legend.position= element in theme() .图例的位置:最后,我们希望将图例移到底部以获得更好的整体外观,可通过theme()legend.position=元素访问。 If you want to keep them on the right, you may want to modify the theme() elements for legend.spacing and legend.margin to get them a bit closer together.如果您想让它们保持在右侧,您可能需要修改legend.spacinglegend.margintheme()元素,使它们更接近一些。

Putting this all together we get the following:将所有这些放在一起,我们得到以下内容:

p +
  scale_fill_manual(NULL, values = 'gray') +
  scale_color_manual(NULL, values = 'red') +
  guides(
    color=guide_legend(override.aes = list(fill=NA), order=1),
    fill=guide_legend(override.aes = list(color=NA), order=2)
  )+
  theme(legend.position = "bottom")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM