Help with stacked bar plot in ggplot
2
1
Entering edit mode
6 weeks ago
Space_Life ▴ 40

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 • 379 views
ADD COMMENT
3
Entering edit mode
6 weeks ago

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.

ADD COMMENT
1
Entering edit mode

Thank you so much. This worked well :)

ADD REPLY
2
Entering edit mode
6 weeks ago
> 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()
ADD COMMENT
0
Entering edit mode

Thank you for your help. :)

ADD REPLY

Login before adding your answer.

Traffic: 1822 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6