Search code examples
rplotggplot2geom-barstacked-chart

geom_bar() draws lines instead of bars


I have the following data:

d <- data.frame(id = rep(2,6), type = c(letters[1:6]), abund = c(27.3,2.7,2.3,2.1,1.2,0.3)) 

  id type abund
1  2    a  27.3
2  2    b   2.7
3  2    c   2.3
4  2    d   2.1
5  2    e   1.2
6  2    f   0.3

I want to create a stacked barplot in ggplot, but when I try it doesn't work correctly:

 library(ggplot2)

 ggplot(data = d, aes(x = abund, y = factor(id), fill = factor(type))) +
    theme_bw() + geom_bar(stat='identity')

What I get (LEFT) and [conceptually*] what I want (RIGHT):

enter image description here enter image description here

I've tried moving around aesthetics and playing with factors, but nothing has worked. This post seemed most similar to mine after an extensive search, but my problem is different.

What do I do??


*I say conceptually, because I drew this in ms paint. I want it to look like a typical ggplot stacked barchart.

Note: my actual desired end result is to have stacked barplots for multiple id groups (i.e., so I have id = rep(2:6, each = 6) using my example)


Solution

  • Perhaps this is what your are looking for. We can flip the x and y axis using coord_flip.

    d <- data.frame(id = rep(2,6), type = c(letters[1:6]), abund = c(27.3,2.7,2.3,2.1,1.2,0.3),
                    stringsAsFactors = FALSE) 
    
    library(ggplot2)
    
    ggplot(data = d, aes(x = factor(id), y = abund, fill = factor(type))) +
      # geom_bar(stat='identity') will also work
      geom_col() +
      # Flip the x and y axis
      coord_flip() +
      theme_bw() 
    

    enter image description here

    Another idea is to use geom_rect, but this requires the creation of xmin, xmax, ymin, and ymax. Therefore, extra work is needed for the original data frame.

    library(dplyr)
    
    d2 <- d %>% 
      mutate(ymin = 0) %>%
      mutate(xmin = lead(abund), xmin = ifelse(is.na(xmin), 0, xmin)) 
    
    ggplot(data = d2, aes(xmin = xmin, xmax = abund, ymin = ymin, ymax = id, 
                          fill = factor(type))) +
      geom_rect() +
      theme_bw()
    

    enter image description here