Open In App

Stacked and Group bar charts in R

Last Updated : 20 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

This article explains how can visualize Stacked and Group bar charts in R Programming Language using ggplot2. 

Stacked and Group bar charts in R

Preparing the data for demonstration:

To create a dataframe we will use the list of elements and then prepare the dataframe for demonstration.

R




# create a dataset
  
# list of elements
vehicle <- c(rep("car" , 3) , rep("bike" , 3) ,
             rep("truck" , 3) , rep("scooter" , 3) )
condition <- rep(c("okay" , "bad" , "worst") , 4)
  
# list generated with random values
pollution <- abs(rnorm(12 , 0 , 15))
  
# preparing the data set
data <- data.frame(vehicle, condition, pollution)
  
# glimpse of the data
cat("Vehicle: ", vehicle)
cat("\nCondition: ", condition)
cat("\nPollution: ", pollution)
  
head(data)


Output:

Grouped Bar Chart

A grouped bar chart (also known as a clustered bar chart or a multi-series bar chart) is a type of bar chart that plots numeric values for two categorical variables rather than one. For levels of one categorical variable, bars are grouped by position, with color representing the secondary category level within each group.

R




# Grouped bar chart plot using the geom_bar()
  
# distinguishing the bar with "condition" parameter
ggplot(data, aes(fill = condition, 
                  
                # y-axis value
                y = pollution, 
  
                # this will group the data
                # based on the "vehicle" type
                x = vehicle)) + 
  
# position adjustment of the bar,
 geom_bar(position = "dodge"
  
          # since we are grouping the bar,
          # we have chosen "dodge"
          stat="identity")


Output:

Stacked Bar Chart

A stacked bar chart is a form of bar chart that may be used to visualize part-to-whole comparisons across time. This makes it easier to represent data in a stacked format. This graph is appropriate for data that is represented in multiple sections and as a whole. This can be used to visualize the steady variation of several factors.

R




# Grouped
# distinguishing the bar with "condition" parameter
ggplot(data, aes(fill = condition, 
                   
                 # y-axis value 
                 y = pollution,
                   
                 # this will group the data
                 # based on the "vehicle" type 
                 x = vehicle)) + 
  
  # position adjustment of the bar,
  geom_bar(position = "stack",  
           # since we are grouping the bar,
           # we have chosen "stack"
           stat="identity")


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads