Search code examples
rggplot2bar-chartstackedbarseries

Add extra value to ggplot barplot


I have the following data:

Sp  Type    Val1    Val2
A   One     200     50
A   Two     100     10
C   One     300     150
C   Two     200     10

I did the following to get stacked barplot:

ggplot() +
  geom_bar(data=test, aes(y = Val1, x = Sp, fill = Type), stat="identity",position='stack')

Hence, I get two stacked bars for A, B each with stacks of Type 1 & 2 (total size of A is 200+100 =300). Here, val2 is a fraction of unknowns in each Type. How do I overlay it in respective portions of stack? i.e in type A in Val1, fraction of unknown is Val2.

Thanks in Advance.

AP


Solution

  • You can try:

    d$xmin <- rep(c(0.55, 1.55),each=2)
    d$xmax <- rep(c(1.45, 2.45),each=2)
    d$ymin <- c(100, 0, 200, 0)
    d$ymax <- c(150, 10, 350, 10)
    
    ggplot(d) + 
        geom_col(aes(x=Sp, y=Val1, fill=Type)) +
        geom_rect(aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), alpha=0.5) 
    

    The idea is to manually add rectangles over the bars (I'm using here geom_col as this function uses stat_identity as default). Thus you calculate the mins and max by yourself and add some alpha to overplot the bars.

    Or you can try a more automatic dplyr solution:

    library(tidyverse)
    d %>% 
      arrange(Sp, -as.numeric(Type)) %>% 
      mutate(ymin=ifelse(Type=="One",lag(Val1),0),
             ymax=ifelse(Type=="Two",Val2, lag(Val1)+Val2)) %>% 
      mutate(Sp_n=as.numeric(Sp)) %>% 
      ggplot() + 
      geom_col(aes(x=Sp_n, y=Val1, fill=Type))+
      geom_rect(aes(xmin=Sp_n-0.45, xmax=Sp_n+0.45, ymin=ymin, ymax=ymax),
      fill="white", alpha= 0.7) +
      scale_x_continuous(breaks = 1:2, labels = unique(d$Sp))
    

    enter image description here