Creating A Grouped Barplot In Base R

In this method of creating a grouped barplot, the user needs just use the base functionalities of the R language. The user needs to first modify the data used to create the bar charts accordingly into different groups and then has to call the barplot() function with the required parameters passed into it to create the barplot of the given data respectively in the R programming language.

Barplot() function: This function is used to create a bar plot with vertical or horizontal bars.

Syntax: barplot(height, beside = FALSE,… )

Parameters:

  • height: either a vector or matrix of values describing the bars which make up the plot. I
  • beside: a logical value. If FALSE, the columns of height are portrayed as stacked bars, and if TRUE the columns are portrayed as juxtaposed bars.
  • …: arguments to be passed to/from other methods.

Example: In this example, we will be creating the grouped barplot of four different groups in the base R.

R




# Create data
gfg <- data.frame(x = c(7,9,8,1,4,6,5,9,6,4,8,5), 
                   grp = rep(c("group 1", "group 2",
                               "group 3","group 4"),
                               each = 3),
                   subgroup = LETTERS[1:3])
# Modifying data
gfg <- reshape(gfg,idvar = "subgroup",
               timevar = "grp",
               direction = "wide")
  
row.names(gfg) <- gfg$subgroup
gfg <- gfg[ , 2:ncol(gfg)]
colnames(gfg) <- c("group 1", "group 2",
                   "group 3","group 4")
gfg <- as.matrix(gfg)
  
# Create grouped barplot
barplot(height = gfg,beside = TRUE)


Output:

How to Create a Grouped Barplot in R?

In this article, we will discuss how to create a grouped barplot in the R programming language.

Similar Reads

Method 1: Creating A Grouped Barplot In Base R

In this method of creating a grouped barplot, the user needs just use the base functionalities of the R language. The user needs to first modify the data used to create the bar charts accordingly into different groups and then has to call the barplot() function with the required parameters passed into it to create the barplot of the given data respectively in the R programming language....

Method 2: Creating A Grouped Barplot Using ggplot2 Package

...

Method 3: Creating A Grouped Barplot Using lattice Package

In this approach to create a group barplot, the user first needs to install and import the ggplot2 package in the working r console, here the ggplot2  is responsible for importing its functions which are in use to create the grouped barplot. Then the user needs to call the geom_bar() function from the ggplot package with the required parameters into it to create the grouped bar plot in the R programming language....