[英]Nested legend based on colour and shape
我想制作嵌套組(組和子組)的 xy 圖,其中點按組着色並按子組具有形狀。 一個最小的例子如下:
DATA<-data.frame(
Group=c(rep("group1",10),rep("group2",10),rep("group3",10) ),
Subgroup = c(rep(c("1.1","1.2"),5), rep(c("2.1","2.2"),5), rep(c("3.1","3.2"),5)),
x=c(rnorm(10, mean=5),rnorm(10, mean=10),rnorm(10, mean=15)),
y=c(rnorm(10, mean=3),rnorm(10, mean=4),rnorm(10, mean=5))
)
ggplot(DATA, aes(x=x, y=y,colour=Group, shape=Subgroup) ) +
geom_point(size=3)
實現您想要的結果的一種選擇是通過ggnewscale
包,它允許多個比例和圖例以實現相同的美感。
為此我們必須
GROUP
拆分數據並通過單獨的geom_point
圖層繪制每個GROUP
。GROUP
都有一個單獨的形狀比例和圖例,通過ggnewscale::new_scale
實現。color
美學,而是將每個組的顏色設置為一個參數,為此我使用了一個命名的顏色向量purrr::imap
循環分割的數據集並動態添加圖層。 還有一點需要注意:一般來說,圖例的順序是通過“魔法算法”默認設置的。 要以正確的順序獲取組,我們必須通過guide_legend
顯式設置順序。
library(ggplot2)
library(ggnewscale)
library(dplyr)
library(purrr)
library(tibble)
DATA_split <- split(DATA, DATA$Group)
# Vector of colors and shapes
colors <- setNames(scales::hue_pal()(length(DATA_split)), names(DATA_split))
shapes <- setNames(scales::shape_pal()(length(unique(DATA$Shape))), unique(DATA$Shape))
ggplot(mapping = aes(x = x, y = y)) +
purrr::imap(DATA_split, function(x, y) {
# Get Labels
labels <- x[c("Shape", "Subgroup")] %>%
distinct(Shape, Subgroup) %>%
deframe()
# Get order
order <- as.numeric(gsub("^.*?(\\d+)$", "\\1", y))
list(
geom_point(data = x, aes(shape = Shape), color = colors[[y]], size = 3),
scale_shape_manual(values = shapes, labels = labels, name = y, guide = guide_legend(order = order)),
new_scale("shape")
)
})
數據
set.seed(123)
DATA <- data.frame(
Group = c(rep("group1", 10), rep("group2", 10), rep("group3", 10)),
Subgroup = c(rep(c("1.1", "1.2"), 5), rep(c("2.1", "2.2"), 5), rep(c("3.1", "3.2"), 5)),
Shape = as.character(c(rep(c(1, 2), 15))),
x = c(rnorm(10, mean = 5), rnorm(10, mean = 10), rnorm(10, mean = 15)),
y = c(rnorm(10, mean = 3), rnorm(10, mean = 4), rnorm(10, mean = 5))
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.