[英]Manual legend in ggplot2 wrong
我想在图形中插入正确的图例。 换句话说,就是传说中的一个红色三角形和一个蓝色圆圈。 下面我展示了一个 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()
在您的示例中,形状不是映射变量,因此指南不会尝试将形状图例(因为它不存在)与颜色图例合并。 您可以使用手动缩放 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")
由代表 package (v0.3.0) 于 2020 年 4 月 18 日创建
或者,您可以在色标中编辑图例本身:
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))))
由代表 package (v0.3.0) 于 2020 年 4 月 18 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.