Create Stacked Bars within Grouped ggplot2 Barchart in R (Example Code)

This post shows how to create stacked bars within a grouped ggplot2 barchart in the R programming language.

Setting up the Example

data(iris)                           # Construct example data
iris_new <- iris
iris_new$Sepal.Width_cat <- "Sepal.Width_large"
iris_new$Sepal.Width_cat[iris_new$Sepal.Width < mean(iris_new$Sepal.Width)] <- "Sepal.Width_small"
iris_new$Petal.Length_cat <- "Petal.Length_large"
iris_new$Petal.Length_cat[iris_new$Petal.Length < mean(iris_new$Petal.Length)] <- "Petal.Length_small"
iris_new <- aggregate(Sepal.Length ~ Species + Sepal.Width_cat + Petal.Length_cat, iris_new, sum)
iris_new                             # Print final data set
#      Species   Sepal.Width_cat   Petal.Length_cat Sepal.Length
# 1 versicolor Sepal.Width_large Petal.Length_large         51.9
# 2  virginica Sepal.Width_large Petal.Length_large        115.7
# 3 versicolor Sepal.Width_small Petal.Length_large        208.1
# 4  virginica Sepal.Width_small Petal.Length_large        213.7
# 5     setosa Sepal.Width_large Petal.Length_small        213.2
# 6     setosa Sepal.Width_small Petal.Length_small         37.1
# 7 versicolor Sepal.Width_small Petal.Length_small         36.8
install.packages("ggplot2")          # Install & load ggplot2
library("ggplot2")

Example: Create Barplot with Stacked Bars within Grouped Barchart

ggplot(iris_new,                     # Draw barplot with grouping & stacking
       aes(x = Sepal.Width_cat,
           y = Sepal.Length,
           fill = Petal.Length_cat)) + 
  geom_bar(stat = "identity",
           position = "stack") +
  facet_grid(~ Species)

r graph figure 1 create stacked bars within grouped ggplot2 barchart r

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top