【发布时间】: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 不,这不会带来预期的结果。