Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

r - 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") 

Barplot

question from:https://stackoverflow.com/questions/65645079/how-to-create-a-stacked-barplot-by-groups-and-subgroups-ggplot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...