'How to create a stacked barplot by groups and subgroups (ggplot)
I have unsuccesfully tried to create a bar plot using ggplot, using the following dataframe:
test <- data.frame(group=c("A", "A", "B", "B"),
gender=c(0,1,0,1),
percent1=c(2,3,4,3),
percent2=c(1,2,0.5,1))
What I want to do, is to create a bar plot. X axis: groups by Letters ('A', 'B'), and split these groups by gender (0 or 1). And Y axis: values of percent1 and percent2 stacked on top of each other
My most 'succesful' solution: I simplified my dataframe, after which the following code gave me the barplot below. However, I did not manage to create subgroups.I have used 'facet_wrap' and 'facet_grid' but consequently failed to create a plot from these.
Question: How do I make this stacked barplot, arranged by groups and subgroups?
# require(ggplot)
# require(reshape)
dfr <- data.frame(percent1 = c(2,3,4,3,1,5),
percent2 = c(1,2,0.5,1,1,1),
row.names = c("A female", "A male", "B female", "B male", "C female", "C male"))
dfr$category <- row.names(dfr)
mdfr<-melt(dfr, id.vars="category")
plot <- ggplot(mdfr, aes(category, value, fill=variable)) +
geom_bar(stat = "identity")

Solution 1:[1]
The issue is that you mixed up gender and group in one variable. Making use of tidyr::pivot_longer to reshape your dataset you could achieve your result like so:
test <- data.frame(group=c("A", "A", "B", "B"),
gender=c(0,1,0,1),
percent1=c(2,3,4,3),
percent2=c(1,2,0.5,1))
library(ggplot2)
library(dplyr)
library(tidyr)
test %>%
mutate(gender = recode(gender, "0" = "male", "1" = "female")) %>%
pivot_longer(starts_with("percent")) %>%
ggplot(aes(gender, value, fill = name)) +
geom_col() +
facet_wrap(~group)

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stefan |
