This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Help with stacked bar plot in ggplot

Hi, I am trying to create a simple stacked bar plot in ggplot. I am probably the only one not getting this one. I went through so many youtube tutorials. All have complex data set examples, but not a simple example. Here is my example data

Example data

I want to get a plot like this.

Desired plot

My trial code that is not working:

type <- rep(c("Type1", "Type2", "Type3")) ggplot(data = data, aes(y = Name, x = type))+ geom_bar(position = "stack", stat = "identity")+ labs(x= "Type", y = "Name")+ theme_classic()

Hope to get your help. Thank you in advance.

bar r ggplot stacked

2 answers

You need to convert your data from wide to long format, and then add Type as a fill aesthetic. It would look something like this.

library("tidyverse")

df %>%
  pivot_longer(!Name, names_to="Type") %>%
  ggplot(aes(x=Name, y=value, fill=Type)) +
    geom_col(position="stack") +
    theme_classic() +
    coord_flip()

See this post for more info on long vs wide data.

Thank you so much. This worked well :)

> library(dplyr)
> library(ggplot2)
> library(tidyr)
> sub_iris=iris %>% 
+     group_by(Species) %>% 
+     sample_n(2)
> sub_iris
# A tibble: 6 × 5
# Groups:   Species [3]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species   
         <dbl>       <dbl>        <dbl>       <dbl> <fct>     
1          4.6         3.2          1.4         0.2 setosa    
2          5           3.5          1.3         0.3 setosa    
3          5.7         3            4.2         1.2 versicolor
4          5           2.3          3.3         1   versicolor
5          6           3            4.8         1.8 virginica 
6          6.3         2.5          5           1.9 virginica 
> sub_iris %>%  
+     pivot_longer(-Species,"type","values")  %>% 
+     ggplot(aes(Species, value, fill=type)) +
+     geom_bar(stat = "identity") +
+     coord_flip() +
+     theme_bw()

Log in to answer this question.