As you can see from the graph below, ggplot automatically change the graphs color based on a second group division (literally group2
).
Now, what I am not able to do is to print a legend for it. I would like under gender with their respective color to be added group2
legend with their respective color or maybe just to manually label them as such.
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 %")
My plot:
CodePudding user response:
Hard to tell what you are trying to achieve, maybe this approach could be useful:
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 %")
Created on 2022-02-07 by the reprex package (v2.0.1)