如何为不同的`stat_smooth`线添加图例,如何将其放在左上角?

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

我有下一个图,我想说明每条线是哪种程度的多项式。

enter image description here

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

我想指出每条线是哪种程度的多项式。但是,我不知道如何在图例中包含这些信息。我也想知道我是否可以将图例放在没有点的地方(左上角)。

r ggplot2 smoothing polynomials
1个回答
1
投票

您可以使用 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)

创建于2020-05-01,由 重读包 (v0.3.0)

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