Stacked and Group bar charts in R
Last Updated :
20 Feb, 2022
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
vehicle <- c ( rep ( "car" , 3) , rep ( "bike" , 3) ,
rep ( "truck" , 3) , rep ( "scooter" , 3) )
condition <- rep ( c ( "okay" , "bad" , "worst" ) , 4)
pollution <- abs ( rnorm (12 , 0 , 15))
data <- data.frame (vehicle, condition, pollution)
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
ggplot (data, aes (fill = condition,
y = pollution,
x = vehicle)) +
geom_bar (position = "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
ggplot (data, aes (fill = condition,
y = pollution,
x = vehicle)) +
geom_bar (position = "stack" ,
stat= "identity" )
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...