简体   繁体   English

ggplot2 中的手动图例错误

[英]Manual legend in ggplot2 wrong

I'd like to insert the correct legend into the graphic.我想在图形中插入正确的图例。 In other words, a red triangle and a blue circle in legend.换句话说,就是传说中的一个红色三角形和一个蓝色圆圈。 Below I showed a MWE.下面我展示了一个 MWE。

df1 <- data.frame(x = 1 : 10, y = rnorm(10))
df2 <- data.frame(x = 1 : 10, y = runif(10))

g <- ggplot()
g <- g + geom_point(aes(x = x, y = y, color = 'color1'), data = df1, shape = 19, size = 2)
g <- g + geom_point(aes(x = x, y = y, color = 'color2'), data = df2, shape = 17, size = 3)
g <- g + scale_colour_manual(breaks = c('color1', 'color2'), 
                             values = c('color1' = 'blue', 'color2' = 'red'))
g + theme_bw()

The shapes aren't mapped variables in your example, so the guide doesn't attempt to merge the shape legend (since it doesn't exist) with the colour legend.在您的示例中,形状不是映射变量,因此指南不会尝试将形状图例(因为它不存在)与颜色图例合并。 You could map the shapes as follows, with a manual scale:您可以使用手动缩放 map 如下形状:

library(ggplot2)
df1 <- data.frame(x = 1 : 10, y = rnorm(10))
df2 <- data.frame(x = 1 : 10, y = runif(10))

g <- ggplot()
g <- g + geom_point(aes(x = x, y = y, color = 'color1', shape = "color1"), 
                    data = df1, size = 2)
g <- g + geom_point(aes(x = x, y = y, color = 'color2', shape = "color2"), 
                    data = df2, size = 3)
g <- g + scale_colour_manual(breaks = c('color1', 'color2'), 
                             values = c('color1' = 'blue', 'color2' = 'red'))
# We need to name the shape legend 'colour' so ggplot knows it belongs to the same legend
g + scale_shape_manual(values = c(19, 17), name = "colour")

Created on 2020-04-18 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 4 月 18 日创建

Alternatively, you can edit the legend itself in the colour scale:或者,您可以在色标中编辑图例本身:

library(ggplot2)
df1 <- data.frame(x = 1 : 10, y = rnorm(10))
df2 <- data.frame(x = 1 : 10, y = runif(10))

g <- ggplot()
g <- g + geom_point(aes(x = x, y = y, color = 'color1'), 
                    data = df1, shape = 19, size = 2)
g <- g + geom_point(aes(x = x, y = y, color = 'color2'), 
                    data = df2, shape = 17, size = 3)
g + scale_colour_manual(breaks = c('color1', 'color2'), 
                        values = c('color1' = 'blue', 'color2' = 'red'),
                        guide = guide_legend(override.aes = list(shape = c(19, 17))))

Created on 2020-04-18 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 4 月 18 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM