Creating A Grouped Barplot Using lattice Package
In this approach to create a grouped barplot, the user first needs to install and import the lattice package in the working R console, then the user needs to call the barchart() function from the lattice package and pass this function with the respective parameters into it to get the grouped barplot in the R programming language.
Syntax to install & import the lattice package in the working R console:
install.package('lattice ') #To Install library(lattice) #To Import
Barchart: This function is used to draw bar plots.
Syntax: barchart(formula, data = parent.frame(), panel = panel.barchart, box.ratio =2, …)
Parameters:
- formula: a formula describing the form of the conditioning plot. A formula of the form y ~ x | g1 * g2 * … indicates that plots of y versus x should be produced conditional on the variable g1,g2,….
- panel: panel function to be used to draw panels
- data: data frame for the variables in the formula etc
- box.ratio: ratio of bar width to inter bar width
- …: other arguments
Example: In this example, we will be creating a grouped barplot using the barchart() function from the lattice package in the R programming language.
R
# Import lattice library (lattice) # 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]) # Create grouped barplot using lattice barchart (x ~ grp, data = gfg, groups = subgroup) |
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.