如何为不同的 `stat_smooth` 行添加图例以及如何将其放置在左上角?

How to add a legend for different `stat_smooth` lines and how to place it in the upper-left corner?

我有下一个剧情:

Plot<- ggplot(df1,aes(x=RMS.V13AP, y=RMS.X16,colour=ID)) + 
  geom_point(size=1) +
  coord_capped_cart(bottom="both",left="both") +
  theme_bw() + 
  labs(x=expression(Acoustic~activity~(m.s^{-2})),y=expression(Real~activity~(m.s^{-2}))) + 
  theme(strip.background=element_blank(),
        axis.title.x =element_text(margin = margin(t = 2, r = 20, b = 0, l = 0),size = 16),
        axis.title.y =element_text(margin = margin(t = 2, r = 20, b = 0, l = 0),size = 16),
        axis.text.x = element_text(angle = 0, hjust = 0.5,size = 12),
        axis.text.y = element_text(angle = 0, hjust = 0.5,size = 14),
        strip.text.x = element_text(size = 14),
        strip.text.y = element_text(size = 13),
        axis.line = element_line(),
        panel.grid.major= element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=12),
        legend.title = element_text(size=12, face = "bold"),
        legend.key=element_blank(),
        legend.position = "top",
        panel.border = element_blank(),
        strip.placement = "outside") +
  scale_x_continuous(breaks=c(0,0.025,0.050,0.075,0.095)) +
  guides(color=guide_legend(override.aes=list(fill=NA),nrow = 1 ))
Plot

Plot <-Plot + stat_smooth(method = "lm",formula= y ~ x, se=FALSE,colour="lightblue") +
  stat_smooth(method = "lm",formula= y ~ x + I(x^2), se=FALSE,colour="skyblue2")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^3), se=FALSE,colour="steelblue2")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^4), se=FALSE,colour="royalblue1")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^5), se=FALSE,colour="blue4") 
Plot

我想指出每一行是哪种次数的多项式。但是,我不知道如何在这些信息中添加图例。我也想知道我是否可以将图例放在没有点的情节区域(左上角)。

您可以使用 ggnewscale 包将多个变量映射到相同的审美(颜色)。然而,这使得图例放置有点奇怪,所以我不知道如何正确放置它。这是 mtcars 数据集的示例。

library(ggplot2)
library(ggnewscale)

ggplot(mtcars, aes(disp, mpg)) +
  geom_point(aes(colour = as.factor(vs))) +
  scale_colour_discrete() +
  new_scale_color() +
  stat_smooth(method = "lm",formula= y ~ x + I(x^2),
              aes(colour = "x^2"), se = FALSE) +
  stat_smooth(method = "lm",formula= y ~ x + I(x^3),
              aes(colour = "x^3"), se = FALSE) +
  stat_smooth(method = "lm",formula= y ~ x + I(x^4),
              aes(colour = "x^4"), se = FALSE)

reprex package (v0.3.0)

于 2020-05-01 创建