1

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)

theforestecologist
  • 4,667
  • 5
  • 54
  • 91

1 Answers1

1

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

www
  • 38,575
  • 12
  • 48
  • 84
  • what in the ???.... could you add an explanation of why I need to do this please? – theforestecologist Jun 17 '18 at 16:02
  • @theforestecologist I have added some brief explanation. You can try to comment out the `coord_flip` line to see the resulting outcome of this function. – www Jun 17 '18 at 16:06
  • 1
    @theforestecologist Added another option with `geom_rect`, although, extrat work is needed for this. – www Jun 17 '18 at 16:13
  • 1
    thanks, @www I appreciate the help on this! I swear, you can learn the intricacies of `ggplot` for a lifetime! – theforestecologist Jun 17 '18 at 16:15