R Tutorial Series: Labeling Data Points on a Plot

There are times that labeling a plot’s data points can be very useful, such as when conveying information in certain visuals or looking for patterns in our data. Fortunately, labeling the individual data points on a plot is a relatively simple process in R. In this tutorial, we will use the Calibrate package’s textxy function to label the points on a scatterplot.

Tutorial Files

Before we begin, you may want to download the sample data (.csv) used in this tutorial. Be sure to right-click and save the file to your R working directory. This dataset contains information used to estimate undergraduate enrollment at the University of New Mexico (Office of Institutional Research, 1990). Note that this tutorial assumes that this data has already been read into R and saved into a variable named enrollmentData.

Plot

To begin, we need to create a scatterplot using the plot(x,y) function. With our example data, we will plot the year on the x axis and the unemployment rate on the y axis.

> #generate a plot using the plot(x,y) function

> #plot year on the x axis and unemployment rate on the y axis

> plot(enrollmentData$YEAR, enrollmentData$UNEM)

For a more detailed description of plotting data in R, see the article on scatterplots.

Textxy

Within the calibrate package, the textxy() function can be used to label a plot’s data points. The textxy() function accepts the following arugments (“Label points in a plot,” n.d.).

Required

x: the x values of the plot’s points

y: the y values of the plot’s points

labs: the labels to be associated with the plot’s points

Optional

cx: used to resize the label font

dcol: used to set the label color; defaults to black

m: sets the origin of the plot; defaults to (0,0)

Here, we will use textxy() to add labels for the enrollment at the University of New Mexico to each of our plot’s data points.

> #if necessary, install the calibrate package

> #install.packages(“calibrate”)

> #load the calibrate package

> library(calibrate)

> #use the textxy() function to add labels to the preexisting plot’s points