Open In App

How to Make Grouped Bar Plot with Same Bar Width in R

In this article, we will discuss How to Make Grouped Bar Plot with the Same Bar Width in R Programming Language.

Method  1 : Using position_dodge2(preserve = “single”)

The geom_col() method can be used to add positions to the graph. Dodging preserves the vertical position of an geom while adjusting the horizontal position. The position_dodge2 method is used to work with bars and rectangle. 



 Syntax : 

position_dodge2(width = NULL, preserve = c("total", "single"))

Parameters: 



Example:




library("ggplot2")
library("ggforce")
 
 
# creating a data frame
df < - data.frame(col1=sample(rep(c(1, 20, 40), each=26)),
                  col2=sample(rep(c(1: 6), each=13))
                  )
 
# plotting the data
df % >%
ggplot(aes(col1, col2))+
geom_col(position=position_dodge2(preserve="single")) +
labs(title="Equal Bar Widths",
     x="col1", y="col2")

Output

Method 2 : Using barplot method

The barplot() method in base R is used to construct successive bar plots from the given input table or matrix. The widths of the bars are equal unless explicitly specified using the width parameter. 

barplot(data, xlab, ylab)

Parameters : 

Example:




# creating a table
df < - table(col1=sample(rep(c(1, 20, 40), each=26)),
             col2=sample(rep(c(1: 6), each=13))
             )
 
 
# plotting the data
# plotting the barplot with equal bar widths
barplot(df, xlab="col1", ylab="col2")

Output


Article Tags :