Draw Stacked Bars within Grouped Barplot in R (Example) | ggplot2 Barchart | facet_grid() & aes()
HTML-код
- Опубликовано: 7 фев 2025
- How to create stacked bars within a grouped ggplot2 barchart in the R programming language. More details: statisticsglob...
R code of this video:
set.seed(687532) # Create example data frame
data <- data.frame(facet = rep(LETTERS[1:5], each = 6),
group = c("x", "y"),
stack = letters[1:3],
value = round(abs(rnorm(30)), 2))
install.packages("ggplot2") # Install & load ggplot2 package
library("ggplot2")
ggplot(data, # Draw barplot with grouping & stacking
aes(x = group,
y = value,
fill = stack)) +
geom_bar(stat = "identity",
position = "stack") +
facet_grid(~ facet)
Follow me on Social Media:
Facebook - Statistics Globe Page: / statisticsglobecom
Facebook - R Programming Group for Discussions & Questions: / statisticsglobe
Facebook - Python Programming Group for Discussions & Questions: / statisticsglobepython
LinkedIn - Statistics Globe Page: / statisticsglobe
LinkedIn - R Programming Group for Discussions & Questions: / 12555223
LinkedIn - Python Programming Group for Discussions & Questions: / 12673534
Twitter: / joachimschork
Music by bensound.com
why was it so hard to find an explanation on how to do this? everyone is just explaining how to do stacked OR grouped but not stacked WITHIN grouped. THANK YOU!
Glad to hear you finally found us! Thank you very much for the feedback!
Hi! Thank you for the in-depth video. I would like to customize the order of my facets (A, B, C, D, E). How can I do so? My dataset was uploaded as a CSV file with 4 headers. The first header contains the facet groups.
Hello Gabriel!
You can try the following:
# Suppose you want to order the facets as "E, D, C, B, A"
# You can reorder the factor levels of `facet` as follows:
data$facet
Hi! Can I have a fifth category? To give you context, I have two groups of stack bars with two different categories. The first group has 4 categories, and the second group has two categories (different from the other 4). The first category is represented by two "structures," and the second is represented by 5 "Scenarios." So, my data frame contains 5 columns: Scenarios (5), Structures (2), Category1 (2), Category2 (7), and Value (Numbers).
Hey, could you explain how your graph should exactly look like?
Hi.. can I know how to overcome error bar overlap when producing a stacked bar chart using R?
Hello Tharindu,
I would expect that they overlap. This is the common setting. See the tutorial: statisticsglobe.com/add-standard-error-bars-barchart-r. But if you still want to locate them somewhere else, where do you like to locate them instead? Also, do you use an error bar per subgroup or one error bar per stacked bar? Accordingly, I can try to help.
Regards,
Cansu
Hello! It is a great video, but, can you kindly simply show it from the raw data till making figure? Many things appeared on the screen, could imagine where they come from. Maybe easy for those who are familiar, but for beginners not easy to understand the process.
Hello Tchister!
You can check the script and the link shared below the video. Here I paste the link: statisticsglobe.com/draw-stacked-bars-within-grouped-barplot-r incase you can't find it. There you will see the script and explanation.
Regards,
Cansu
Could you prepare The best books in R.
Hey Shaafici, please have a look here: statisticsglobe.com/statistics-data-science-programming-resources
@@StatisticsGlobeyo preferiría un curso completo de gestión se datos con tidyverse, pero completo, desde la comprensión de la gramática del lenguaje a su aplicación práctica.
How would you add the error bars on a stacked barplot with ggplot2 in R (on the same format plot as your plot, with different panels)?
Hello Andrea,
I was on vacation in the last weeks. Do you still need help?
Best,
Cansu
@@cansustatisticsglobe Hello, I’ve just gave up with plotting that graph in R. I just kept R for statistical analysing. The issue was that when trying to add the error bars(standard deviation) the vertical lines were randomly plotted on bars. In other words, I think R didn’t recognize the two different set of data from the same bar. For stacked bar (with two data set) R assigned the both error lines in the middle of the bar (taking into account only one data). I hope this makes sense. If not, it’s ok and I will try to figure it when I will have more time for this.
Right now, I have only one week left until submitting my master thesis😁 Enjoy your day!
Hello @@andreeaalexandra4654,
What are you aiming to show by doing it? If you would like to show the group means and the related standard errors, I am not sure if the stacked barplot is the best option considering that the sum of mean values will be shown on the y-axis instead of the absolute means. I would rather suggest using dodged bar chart. See here: bioinformatics.stackexchange.com/questions/11222/stacked-bargraph-with-error-bars. However, if you still want to use a stacked barplot knowing that the error bars will be located at the coordinates of the mean sums, then you can use the following code, which adds the error bars manually.
library(dplyr)
summary_data %
group_by(group, category) %>%
summarise(mean_value = mean(value),
se = sd(value) / sqrt(n()))%>%
arrange(group, desc(category))%>%
mutate(sum_mean = cumsum(mean_value),
sum_mean_min = sum_mean - se,
sum_mean_max = sum_mean + se)
summary_data
# group category mean_value se sum_mean sum_mean_min sum_mean_max
#
# 1 A y 1.09 0.164 1.09 0.923 1.25
# 2 A x 1.58 0.640 2.67 2.03 3.31
# 3 B y 0.98 0.166 0.98 0.814 1.15
# 4 B x 0.727 0.452 1.71 1.25 2.16
# 5 C y 0.19 0.0808 0.19 0.109 0.271
# 6 C x 1.04 0.788 1.23 0.445 2.02
# 7 D y 0.84 0.400 0.84 0.440 1.24
# 8 D x 0.713 0.380 1.55 1.17 1.93
# 9 E y 0.673 0.466 0.673 0.207 1.14
# 10 E x 0.923 0.313 1.60 1.28 1.91
library(ggplot2)
ggplot(summary_data, aes(x = group, y = mean_value, fill = category)) +
geom_bar(stat = "identity") +
geom_errorbar(aes(ymin = sum_mean_min,
y = sum_mean,
ymax = sum_mean_max),
position = "identity") +
labs(title = "Stacked Barplot with Error Bars",
y = "Mean Value",
x = "Group") +
theme_minimal()
The data is the dataset used in the tutorial. I have just created summarized data called summary_data to plot the error bars. Please be aware that the coordinates of error bars are based on the sum of means to place them on the top of each stack. I hope this solution helps you well. And I wish you the very best for your thesis.
Best,
Cansu