Basic skills in R: Basic graphics
General information about graphics in R
R has many tools for making beautiful data graphics, such as scatter plots, histograms, bar charts, boxplots, and much more, which are standard (in the so-called 'base R' environment) available to you, i.e. without the need of loading and using additional packages. In this section, we will focus on learning to use the graphics functions in base R. This will also help you understand and appreciate more advanced graphics packages like ggplot2
, which will be discussed elsewhere.
The painter's model You can think of an R graphic as being much like a painting. You start out with an empty canvas. Every time you use a graphics function, it paints some new things onto your canvas. Later on, you can paint more things over the top if you want; but just like painting, you
can't undo your strokes. This way of thinking about drawing graphs is referred to as the painter's model.
Firstly, if you want to paint a picture, you need to paint it on something, which is called in R a 'device'. In RStudio, the device called RStudioGD forces R to paint inside the Plots panel in Rstudio. But R can also to paint pictures directly into a file; jpeg, png, pdf, postscript, tiff and bmp are some of the common image formats available to you. Secondly, when you paint a picture you need to paint it with something. This is called the graphics system and in base R this is a collection of basic graphics commands about what to draw and where to draw it.
The broad picture of creating graphics in R The painter's model implies that there are two steps involved when creating a plot:
- Initializing a new plot;
- Annotating (adding to) an existing plot.
Some instructions will perform both these two steps at once. For example, the commands plot(x, y)
or hist(x)
will launch a graphics device (if one is not already open) and draw a new plot on the device in one go.
Many graphics functions (like plot(x, y)
or hist(x)
) have various additional input arguments, which you can use to specify the title, x axis label, y axis label, colour of lines and points, and so on. The base graphics system has many global parameters that can be set and tweaked to create graphics to your liking. Global parameters specify the default settings for plots (for example the sizes of margins, axis orientation, size of fonts, etc.). The function par()
can be used to query or set graphical parameters. By practice you will start to know some of these parameters by heart, which will speed up the graph making process.