Draw Stacked Bars within Grouped Barplot in R (Example) | ggplot2 Barchart | facet_grid() & aes()

Published 2022-08-13
How to create stacked bars within a grouped ggplot2 barchart in the R programming language. More details: statisticsglobe.com/draw-stacked-bars-within-group…
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: www.facebook.com/statisticsglobecom/
Facebook – R Programming Group for Discussions & Questions: www.facebook.com/groups/statisticsglobe
Facebook – Python Programming Group for Discussions & Questions: www.facebook.com/groups/statisticsglobepython
LinkedIn – Statistics Globe Page: www.linkedin.com/company/statisticsglobe/
LinkedIn – R Programming Group for Discussions & Questions: www.linkedin.com/groups/12555223/
LinkedIn – Python Programming Group for Discussions & Questions: www.linkedin.com/groups/12673534/
Twitter: twitter.com/JoachimSchork

Music by bensound.com

All Comments (8)
  • @lauramsolarte
    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).
  • @Melixanne
    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!
  • 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.
  • @Fly_maggot
    Hi.. can I know how to overcome error bar overlap when producing a stacked bar chart using R?
  • 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! 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.