# How to create a boxplots using lattice package in R?

Last Updated : 11 Jul, 2022

In this article, we will discuss how to create the boxplots using lattice package in R Programming language.

In R programming, Lattice package is a data visualization library and consists of various functions to plot different kind of plots. Using lattice library we can able to plot different plots like scatter plot, Box plots, Histograms, 3D scatter plots, Dot plots, Strip plots, Density plots etc. In order to use the functionalities of lattice library need to import the library first.

## Box plot using lattice package

In R, The Lattice library contains bwplot() method that is used to create a box plot. In order to use the bwplot() method, the lattice library need to be imported first. The syntax of bwplot() method is given below-

bwplot( col1~col2, data=dataframeName, xlab=”x-label”, ylab=”y-label”, panel=panel.violin)

Let’s look into a couple of examples on how to plot the box plot using the lattice library.

Example 1: In the below code we created a data frame “stats” and plotted a box plot between data in two columns using bwplot() method.

## R

 `library``(lattice) ` ` `  `# create a data frameÂ  ` `stats <- ``data.frame``(player=``c``(``'A'``, ``'B'``, ``'C'``, ``'D'``, ` `                             ``'E'``, ``'F'``, ``'G'``, ``'H'``), ` `               ``runs=``c``(200, 100, 100, 150, 109, ` `                      ``200, 500, 120), ` `               ``wickets=``c``(10, 10, 31, 20, 34, 20, ` `                         ``34, 26)) ` ` `  `print``(``"stats Dataframe"``) ` `stats ` ` `  `bwplot``(runs ~ wickets, data = stats, xlab = ``"runs"``,  ` `       ``ylab = ``"wickets"``)`

Output

```"stats Dataframe"
player runs wickets
1      A  200      10
2      B  100      10
3      C  100      31
4      D  150      20
5      E  109      34
6      F  200      20
7      G  500      34
8      H  120      26```

Example 2: In this example, we plotted a violin plot for the above created data frame using bwplot() method by passing panel.violin value to the bwplot() method.

## R

 `# import lattice library ` `library``(lattice) ` ` `  `# create a data frameÂ  ` `stats <- ``data.frame``(player=``c``(``'A'``, ``'B'``, ``'C'``,  ` `                             ``'D'``, ``'E'``, ``'F'``,  ` `                             ``'G'``, ``'H'``), ` `               ``runs=``c``(200, 100, 100, 150, 109, ` `                      ``200, 500, 120), ` `               ``wickets=``c``(10, 10, 31, 20, 34,  ` `                         ``20, 34, 26)) ` ` `  `bwplot``(runs ~ wickets, data = stats,  ` `       ``xlab = ``"runs"``, ylab = ``"wickets"``,  ` `       ``panel=panel.violin)`

Output

Previous
Next