我正在嘗試使用 ggarrange 將幾個情節的圖例組合成一個情節。但是,情節 1 中的某些元素不在情節 2 中,反之亦然。因此,ggarrange 中的 common.legend 選項不起作用。我的代碼(最小的作業示例)如下:
library(tidyverse)
library(ggpubr)
data("mtcars")
mtcars1 <- mtcars %>%
filter(gear == 3 | gear ==4)
p1 <- ggplot(mtcars1, aes(x=wt, y=mpg, color = factor(gear)))
geom_point()
scale_color_manual(values = c('red', 'blue'))
mtcars2 <- mtcars %>%
filter(gear == 3 | gear ==5)
p2 <- ggplot(mtcars2, aes(x=wt, y=mpg, color = factor(gear)))
geom_point()
scale_color_manual(values = c('red', 'green'))
ggarrange(p1,p2, common.legend = TRUE)
這導致以下情節:

這里的問題是常見的圖例不包含綠色(即齒輪 5)。我想知道如何創建一個包含所有元素的組合通用圖例。
此外,我希望有一種方法可以將傳奇與例如榮譽進行分組。所以假設我有以下傳說
檔位 3 低 4 低 5 中
然后我想將兩個低點合并為一個低點,并獲得榮譽或類似的東西。像這樣:
檔位 3 } 低檔 4
5 } 中等
uj5u.com熱心網友回復:
在將gear變數視為因子時,請指定三個水平,即使第三個水平在資料集中不可用。然后,在 中scale_color_manual,分別指定值的顏色并包含引數drop = FALSE)。
mtcars1 <- mtcars %>%
filter(gear == 3 | gear ==4)
p1 <- ggplot(mtcars1, aes(x=wt, y=mpg, color = factor(gear, levels = c(3, 4, 5))))
geom_point(show.legend = TRUE)
scale_color_manual(name = 'Gear',
values = c("3" = 'red', "4" = 'blue', "5" = 'green'),
drop = FALSE)
mtcars2 <- mtcars %>%
filter(gear == 3 | gear ==5)
p2 <- ggplot(mtcars2, aes(x=wt, y=mpg, color = factor(gear, levels = c(3, 4, 5))))
geom_point(show.legend = TRUE)
scale_color_manual(name = 'Gear',
values = c("3" = 'red', "4" = 'blue', "5" = 'green'),
drop = FALSE)
ggarrange(p1,p2, common.legend = TRUE)
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529687.html
標籤:rggplot2
