rggplot2geom-barstackedbarseries

Stacked bar in ggplot2, with 2 series of bars (different columns)


Dataset:

I have a dataset as the following: http://www.sharecsv.com/s/786597b1557929e190edf69a46f1dec4/example.csv

Three columns, with YES/NO answers on each.


Problem:

I need to make a stacked bar chart, where A is the horizontal axis. I need two have two stacked bars side by side (one for B column data, one for C column data).

I tried grouping the data as follows, but it doesn't produce the outcome I need:

sum_data <- wsheet %>% group_by(A, B, C) %>% summarise(count = n())

I need both B and C summarised only in terms of A, to be able to put it in the plot.

The following is the incorrect plot I am achieving. I basically need another stacked column for C besides B, for each value of A.

enter image description here


Closest Attempt

I still didn't get the chart that I wanted, but this is the closest that I have:

  1. Did to grouped sub-datasets:
sub_b <- wsheet %>% group_by(A, B) %>% summarise(count = n())
colnames(sub_b) <- c("A", "value", "count")
sub_b$measure <- "B"

sub_c <- wsheet %>% group_by(A, C) %>% summarise(count = n())
colnames(sub_c) <- c("A", "value", "count")
sub_c$measure <- "C"
  1. Bound them together:
sub_both <- rbind(sub_b, sub_c)
  1. Made a facetted graph:
ggplot(sub_both) +
  geom_bar( aes(x = A, y = count, fill = value), stat = "identity") +
  facet_wrap(~measure)

enter image description here

What did I wanted?

To have B and C bars side by side, instead of facetted.


Solution

  • Update code:

    #Read data
    wsheet <- read.csv('example.csv')
    #Data transform
    sub_b <- wsheet %>% group_by(A, B) %>% summarise(count = n())
    colnames(sub_b) <- c("A", "value", "count")
    sub_b$measure <- "B"
    
    sub_c <- wsheet %>% group_by(A, C) %>% summarise(count = n())
    colnames(sub_c) <- c("A", "value", "count")
    sub_c$measure <- "C"
    
    #Create variables
    
    sub_both <- rbind(sub_b, sub_c)
    sub_both$var <- paste0(sub_both$A,'.',sub_both$measure)
    
    #Plot
    
    ggplot(sub_both) +
      geom_bar( aes(x = var, y = count, fill = value), stat = "identity")
    

    enter image description here