[英]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.