如何在 ggplot (R) 中添加第二组图例?
How to add a second group legend in ggplot (R)?
正如您从下图中看到的,ggplot 根据第二组划分(字面意思是 group2
)自动更改图表颜色。
现在,我无法做的是为它打印一个图例。我想在具有各自颜色的性别下添加 group2
具有各自颜色的图例,或者可能只是手动标记它们。
set.seed(34)
data <- data.frame(gender = rep(c("female", "male"), length.out=10),
group2 = sample(letters[1:2], 10, replace = T),
group = rep(letters[11:13], length.out=10),
nums = as.integer(runif(10, min=10, max=500)))
xc <- data %>%
group_by(group) %>%
mutate(sum=sum(nums)) %>%
group_by(gender, group2, group) %>%
mutate(prop = nums/sum*100)
ggplot(xc, aes(x=group, fill = gender, color = group2, y = prop)) +
geom_col(position="dodge", color = "white", alpha = 0.85) +
scale_fill_manual(values = c("#466760","#845574")) +
theme_minimal() +
theme() +
ggtitle("") +
xlab("") +
ylab("Percentage %")
我的剧情:
很难说出您要实现的目标,也许这种方法可能有用:
library(dplyr)
library(ggplot2)
ggplot(xc, aes(x = gender, y = prop, fill = group2)) +
geom_col(position = position_dodge2(preserve = "single", padding = 0.01), alpha = 0.85) +
scale_fill_manual(values = c("#466760", "#845574")) +
facet_wrap(~group, nrow = 1)+
theme_bw() +
theme(panel.border = element_blank()) +
ggtitle("") +
xlab("") +
ylab("Percentage %")
由 reprex package (v2.0.1)
创建于 2022-02-07
正如您从下图中看到的,ggplot 根据第二组划分(字面意思是 group2
)自动更改图表颜色。
现在,我无法做的是为它打印一个图例。我想在具有各自颜色的性别下添加 group2
具有各自颜色的图例,或者可能只是手动标记它们。
set.seed(34)
data <- data.frame(gender = rep(c("female", "male"), length.out=10),
group2 = sample(letters[1:2], 10, replace = T),
group = rep(letters[11:13], length.out=10),
nums = as.integer(runif(10, min=10, max=500)))
xc <- data %>%
group_by(group) %>%
mutate(sum=sum(nums)) %>%
group_by(gender, group2, group) %>%
mutate(prop = nums/sum*100)
ggplot(xc, aes(x=group, fill = gender, color = group2, y = prop)) +
geom_col(position="dodge", color = "white", alpha = 0.85) +
scale_fill_manual(values = c("#466760","#845574")) +
theme_minimal() +
theme() +
ggtitle("") +
xlab("") +
ylab("Percentage %")
我的剧情:
很难说出您要实现的目标,也许这种方法可能有用:
library(dplyr)
library(ggplot2)
ggplot(xc, aes(x = gender, y = prop, fill = group2)) +
geom_col(position = position_dodge2(preserve = "single", padding = 0.01), alpha = 0.85) +
scale_fill_manual(values = c("#466760", "#845574")) +
facet_wrap(~group, nrow = 1)+
theme_bw() +
theme(panel.border = element_blank()) +
ggtitle("") +
xlab("") +
ylab("Percentage %")
由 reprex package (v2.0.1)
创建于 2022-02-07