ggplot图例:geom_abline干扰

Pat*_*ckT 3 r ggplot2

目标:有一个颜色图例,用于geom_point显示每组的一个彩色点,以及一个用于geom_abline显示每条线的一个彩色线的图例。

难道我做错了什么?有解决办法吗?

# data: mtcars + some made-up straight lines
library(ggplot2)
df = data.frame(Intercept = c(2,3,4), Slope = c(0,0,0), Group = factor(c(1, 2, 3)))
Run Code Online (Sandbox Code Playgroud)

关于#1 的评论:基本图没有什么特别的,但我已将数据分组到 中,aes()并将颜色设置为aes()。我认为在 aes 中同时包含“group”和“color”以实现分组和着色是标准的。

# 1. my basic plot
ggplot(data = mtcars, aes(x = mpg, y = wt, group = vs, color = factor(vs))) + 
    geom_point() -> p
Run Code Online (Sandbox Code Playgroud)

关于 #2 的评论:显然我没有设置ggplot正确处理图例的权利。我还尝试添加到group = Groupaes 内部。但有一个更严重的问题:geom_point 形成 2 组,geom_abline 形成 3 组,但图例仅显示 4 种颜色/线条组合。其中之一已合并(绿色的)。我在这里做错了什么?

# 2. my naive attempt to add ablines of 3 different colours
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                           colour = Group))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

关于 #3 的评论:图例中的 ablines 已被删除,但点仍然不正确。从这里开始,它变得越来越绝望。

# 3. Suppress the ab_line legend?
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                           colour = Group), show.legend = FALSE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

关于 #4 的评论:这就是我目前要做的。没有传说比错误的传说好。但遗憾的是失去了颜色。

# 4. Remove the geom_abline legend AND colors
p + geom_abline(data = df, aes(intercept = Intercept, slope = Slope))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

评论#5:我不知道我在这里希望什么...如果我在调用中定义数据和 aesgeom_point()而不是ggplot(),不知何故geom_abline())不会劫持颜色和图例,但不,它似乎没有做出改变。

# 5. An attempt to set the aes inside geom_point() instead of ggplot()
ggplot() + 
    geom_point(data = mtcars, aes(x = mpg, y = wt, group = vs, color = factor(vs))) + 
    geom_abline(data = df, aes(intercept = Intercept, slope = Slope, color = "groups")) +
    scale_color_manual(values = c("red", "blue", "black"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

And*_*tar 5

一种选择是对数据使用填充形状mtcars,然后您可以拥有一个fill比例和一个colour比例,而不是两个colour比例。colour="white"如果您不想要黑色轮廓,您可以在语句中添加一个选项geom_point,以便更改点边缘的颜色。

library(ggplot2)
df = data.frame(Intercept = c(2,3,4), Slope = c(0,0,0), Group = factor(c(1, 2, 3)))
ggplot(data = mtcars, aes(x = mpg, y = wt, group = vs, fill = factor(vs))) + 
           geom_point(shape=21, size=2) +
           geom_abline(data = df, aes(intercept = Intercept, slope = Slope,
                              colour = Group))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述