【问题标题】:How to include loess line in ggplot2 legend?如何在ggplot2图例中包含黄土线?
【发布时间】:2026-01-10 04:50:01
【问题描述】:

我想在图例中附上绿色的黄土线。我尝试使用this solution,但我不知道如何将线型设置为黄土线(第一个stat_smooth())。我该怎么做?它应该显示在现有图例的右侧:----- loess

library(ggplot2)
ggplot(mtcars, aes(wt, mpg, color=as.factor(vs), group=as.factor(vs))) +
  stat_smooth(method="loess", se=FALSE, color="green", 
              lty=2, show.legend=TRUE,
              aes(group=as.factor(vs))) +
  stat_smooth(method="lm", formula=y ~ poly(x, 2, raw=TRUE),
              se=FALSE, show.legend=TRUE)+
  theme_minimal()+
  # scale_linetype_manual("foo", values="green") +  # won't work
  # guides(linetype=guide_legend(override.aes=list(color="black"))) +  # won't work either
  guides(color = guide_legend(direction = "horizontal")) +
  theme(legend.position = c(0, 1), 
        legend.justification = c("left", "top"),
        legend.box.just = "right")

【问题讨论】:

  • 很难理解你想要什么。例如,您有 4 个颜色规格:主函数color=as.factor(vs);第一次平滑col="green"color=as.factor(vs);第二次顺利color=as.factor(vs)。我将从删除冗余代码开始(主函数中的颜色应该没问题)。
  • @PoGibas 好的,我减少了代码,感谢您的提示。通过这样做,我注意到当我删除color="green 时,黄土平滑具有与相关曲线相同的颜色。所以你建议把他们分开?那我该怎么做呢?
  • 在你的情况下,我会在第一次平滑时使用aes(linetype = factor(vs)) 而不是`lty=2`
  • @PoGibas 不,这不会带来预期的结果。

标签: r ggplot2 legend


【解决方案1】:

您可以引入一个空因子并将其调整为看起来像黄土图。

library(ggplot2)
library(tidyverse)

mtcars2 <- mtcars %>% 
  mutate(vs2 = factor(vs, levels = c("0", "1", "dotted")
                      , labels = c("0", "1", "dotted")))

ggplot(mtcars2, aes(wt, mpg, color=vs2, linetype=vs2)) +
stat_smooth(method="loess", se=FALSE, color="green", 
            lty=2, show.legend=TRUE,
            aes(group=vs2)) +
stat_smooth(method="lm", formula=y ~ poly(x, 2, raw=TRUE),
            se=FALSE, show.legend=TRUE)+
theme_minimal() +
  scale_color_manual(values = c("red", "blue", "green"), drop = FALSE) +
  scale_linetype_manual(values = c(1, 1, 2), drop = FALSE)

【讨论】:

  • 不错的解决方案。从我的原始代码中丢弃guides(.) 并更新theme(legend.direction = "horizontal"),这完全符合预期。谢谢!
【解决方案2】:

对于loess 平滑器,映射 colorlinetypeaes 中的字符串常量,使其以适当的标签出现在图例中。使用 guides(..., override.aes(...) 更改结果图例中的线型

mtcars$vs <- as.factor(mtcars$vs)
ggplot(mtcars, aes(wt, mpg, color = vs, group = vs, linetype = vs)) +
  stat_smooth(aes(color = "loess", linetype = "loess"), method = "loess", se = FALSE) +
  stat_smooth(method = "lm", formula = y ~ poly(x, 2, raw= TRUE), se = FALSE, show.legend = TRUE) +
  scale_color_manual(values = c("red", "blue", "green")) +
  scale_linetype_manual(values = c(1, 1, 2)) +
  guides(color = guide_legend(override.aes = list(linetype = c(1, 1, 2)))) +
  theme_minimal()

【讨论】: