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

标签 r ggplot2 legend

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

相关文章:

r - 从多个txt文件创建语料库

r - 使用 geom_line 绘制多条线(基于分组)

r - ggplot2 绘制两个图例

html - 图例不会在 IE7 上向左浮动

python - Python 中的 Fama Macbeth 回归(Pandas 或 Statsmodels)

r - R 中 2 个向量的投影

r - 使用 ggplot2 在 R 中绘制等倾线

r - 在 ggplot2 中的条之间添加空间

matlab - 如何自定义图例元素的位置?

r - 如何重新排序 R 中列表中所有数据框的列?