How to create stacked rods in a grouped barchart in R

I have the following chart

test <- data.frame(person=c("A", "B", "C", "D", "E"), value1=c(100,150,120,80,150), value2=c(25,30,45,30,30) , value3=c(100,120,150,150,200)) 

I want to build a grouped barcher (horizontal) for each person, where one strip shows the value1, and the other - the stack of value2 and value3. Is there any way I can do this using ggplot2? Can I use faces to plot these separate graphs one below the other?

+4
source share
1 answer

Here's what I came up with, similar to the solution proposed here: folded columns in a grouped histogram

  • Melt the data.frame and add a new cat column

     library(reshape2) # for melt melted <- melt(test, "person") melted$cat <- '' melted[melted$variable == 'value1',]$cat <- "first" melted[melted$variable != 'value1',]$cat <- "second" 
  • Build a complex cat vs value diagram, face on person . You may need to configure shortcuts to get what you want:

     ggplot(melted, aes(x = cat, y = value, fill = variable)) + geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ person) 

enter image description here

+22
source

Source: https://habr.com/ru/post/1501943/


All Articles