gpt4 book ai didi

r - 如何在ggplot2图例中包含黄土线?

转载 作者:行者123 更新时间:2023-12-04 11:05:52 27 4
gpt4 key购买 nike

我想把图例中的青黄土线圈起来。我试过 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")

enter image description here

最佳答案

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

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)

enter image description here

关于r - 如何在ggplot2图例中包含黄土线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446489/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com