r - 如何在ggplot2图例中包含黄土线?
问题描述
我想在图例中附上绿色的黄土线。我尝试了这个解决方案,但我不知道如何将线型设置为黄土线(第一个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")
解决方案
您可以引入一个空因子并将其调整为看起来像黄土图。
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)
推荐阅读
- python - 您是否必须在 Mac 上安装 python 才能运行 Platypus 应用程序?
- spring - 在 Spring 路由定义中使用谓词不起作用
- c# - C# 无法下载 XML 作为附件
- php - 将搜索数据保存到文本文件是否安全?
- mysql - sql字符串在没有准备好的语句的情况下执行
- java - 从字符串中删除元音 - 我得到的答案与输入相同。你能告诉我为什么吗?
- python - 如何在 Python 3 中选择字符串的某些部分?
- java - 我不知道如何完成此代码以显示收藏夹列表
- opencv - 如何通过命令行(Ubuntu)编译 OpenCV 程序?
- java - 如何在 Netbeans 中编写 JFrame 而不是拖放?