Home > Enterprise >  How to make a stacked bar plot in R
How to make a stacked bar plot in R

Time:07-16

I have a data set that has information regarding 13 different teams (A:M). With each team, there is a variable for the total amount of people on each team, along with three different numeric variables for different characteristics measured. The code below is an example of what I'm trying to work with:

Team <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M")
total <- c(557, 3, 3116, 201, 167, 1348, 877, 1444, 2, 1003, 25, 732, 2532)
characteristic1 <- c(111, 0, 566, 45, 77, 600, 356, 300, 0, 402, 3, 278, 312)
characteristic2 <- c(20, 0, 231, 14, 15, 27, 30, 78, 0, 48, 0, 29, 111)
characteristic3 <- c(1, 0, 29, 1, 0, 10, 11, 3, 0, 2, 9, 1, 3)

df <- data.frame(Team, total, characteristic1, characteristic2, characteristic3)

What I would like to do is make a stacked (or grouped) bar plot where x is each separate team. The largest bar on each team will be the total amount of people on each team. And then I'd like to have stacked bars within each representing characteristic1, characteristic2, and characteristic3. I've also thought about doing each characteristic as a percentage of the total, but either way, I'm not sure how to go about making a bar plot to represent everything. I'd also be open to any suggestions of other ways to best represent this information that would not be in the form of a barplot. Any help would be greatly appreciated!

CodePudding user response:

Main feature is to bring your data in long format. The challenging thing here may be the total column. But we could treat it just as another group member:

library(tidyverse)

df %>% 
  pivot_longer(-Team) %>%
  ggplot(aes(x=Team, y= value, fill = name))  
  geom_col(position= position_dodge())

If you want a stacked bar then use position_stack() or position_fill() instead of position_dodge()

enter image description here

  • Related