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 FilesBefore 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.
PlotTo 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.
TextxyWithin 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.).
- 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
- 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)
- > #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
- > #add labels for the total enrollment
- > textxy(enrollmentData$YEAR, enrollmentData$UNEM, enrollmentData$ROLL)
In this case, adding labels to our data points helps us to better assess the relationships in our dataset.
Complete Data Point Labeling ExampleTo see a complete example of how a plot’s data points can be labeled in R, please download the Data Point Labeling (.txt) file.
ReferencesLabel points in a plot. (n.d.). Retrieved September 19, 2010 from http://rss.acs.unt.edu/Rdoc/library/calibrate/html/textxy.html
Office of Institutional Research (1990). Enrollment Forecast [Data File]. Retrieved November 22, 2009 from http://lib.stat.cmu.edu/DASL/Datafiles/enrolldat.html