Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce stacked bars within grouped barchart in R [duplicate]

I have the following graph

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 plot a grouped barchart (horizontal) for each person where one bar indicates value1 and the other bar is stack of value2 and value3. Is there a way with which I can do this using ggplot2? Can I use facets to plot these individual graphs one below the other?

like image 761
Sudhi Avatar asked Sep 12 '13 21:09

Sudhi


People also ask

How do you make a stacked barplot in R?

In order to create a stacked bar chart, also known as stacked bar graph or stacked bar plot, you can use barplot from base R graphics. Note that you can add a title, a subtitle, the axes labels with the corresponding arguments or remove the axes setting axes = FALSE , among other customization arguments.

How do you combine two bar plots?

Highlight the second set of data, making sure to unhighlight the first set of data. Press "Ctrl+c" to copy the information. Click on the graph and press "Ctrl+v." This should insert the second set of information into the graph. Repeat for any other pieces of information.


1 Answers

Here is what I came up with, similar to a solution proposed here: stacked bars within grouped bar chart

  1. Melt data.frame and add a new column cat

    library(reshape2) # for melt
    
    melted <- melt(test, "person")
    
    melted$cat <- ''
    melted[melted$variable == 'value1',]$cat <- "first"
    melted[melted$variable != 'value1',]$cat <- "second"
    
  2. Plot a stacked chart cat vs value, faceting by person. You may need to adjust the labels 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

like image 192
Victor K. Avatar answered Oct 13 '22 23:10

Victor K.