 How to Make Common Graphs with Lattice in R - dummies

# How to Make Common Graphs with Lattice in R

While the lattice graphics package features a long list of graphic types in R, bar charts and box-and-whisker plots are among the most commonly used.

## How to make a lattice bar chart in R

To make a bar chart, use the lattice function barchart(). Say you want to create a bar chart of fuel economy for each different type of car. To do this, you first have to add the names of the cars to the data itself. Because the names are contained in the row names, this means assigning a new column in your data frame with the name cars, containing rownames(mtcars):

`> mtcars\$cars <- rownames(mtcars)`

Now you can create your bar chart using similar syntax to the scatterplot you made earlier:

```> barchart(cars ~ mpg | factor(cyl), data=mtcars,
+   main="barchart",
+   scales=list(cex=0.5),
+   layout=c(3, 1)
+ )```

Once again (because you have eagle eyes), you’ve noticed the additional argument layout in this code. Lattice plots adapt to the size of the active graphics window on your screen. They do this by changing the configuration of the panels of your plot. For example, if your graphics window is too narrow to contain the panels side by side, then lattice will start to stack your panels.

You control the layout of your panels with the argument layout, consisting of two numbers indicating the number of columns and number of rows in your plot. In our example, you want to ensure that the three panels are side by side, so it’s specified to use layout=c(3, 1). ## How to make a lattice box-and-whisker plot in R

A box-and-whisker plot is useful when you want to visually summarize the uncertainty of a variable. The plot consists of a dark circle at the mean; a box around the upper and lower hinges (the hinges are at approximately the 25th and 75th percentiles); and a dotted line, or whisker, at 1.5 times the box length.

The lattice function to create a box and whisker plot is bwplot().

Notice that the function formula doesn’t have a left-hand side to the equation. Because you’re creating a one-dimensional plot of horsepower conditional on cylinders, the formula simplifies to ~ hp | cyl. In other words, the formula starts with the tilde symbol: `> bwplot(~ hp | factor(cyl), data=mtcars, main="bwplot")`

With lattice graphics, you can create many different types of plots in R. Here are just a few of the different types of plots you can create other than the bar chart and the box-and-whisker plot:

• Scatterplot: xyplot()

• One-dimensional strip plot: stripplot()

• Three-dimensional scatterplots: cloud()

• Three-dimensional surface plots: wireframe()

For a complete list of the different types of lattice plots, see the Help at ?lattice.