Skip to Main Content

Intro to R Programming

R is a powerful tool for data analysis and visualization; this guide will provide resources to get you started with this programming language!

Why use R to make graphs?

Excel, GraphPad Prism, or other graphical software are sufficient when creating basic graphs, but R packages can extend data visualization capabilities. 

  • R code is great for reproducibility, as you can run the same code on different data sets and others can easily replicate your graphs.
  • In R, you can easily modify aesthetics of a graph with more customization control (i.e., changing only one point/error bar of the graph rather than changing the entire color scheme of the graph).

Graphing in R is like painting and uses a canvas approach; you start out with an empty plot (called a device). You'll add your data points, axis titles, graph title, color customizations, and other functions individually. Each time a graphics function is used, R 'paints' the new customizations onto your plot device.

Graphics using Base R

R itself comes pre-loaded with basic R graphics functions:

Base R Function Type of Graph Graph Description
barplot() bar graph categorical data with bars with heights/lengths proportional to the values
boxplot()  box-and-whisker plot shows distribution of data points through quartiles
dotchart() Cleveland dotplot an alternative to a bar graph; plots a dot for each observation on a scale
hist() histogram distribution of numerical data
plot() scatterplot plotted dots represent values for two numeric variables on the horizontal and vertical axes
pie() piechart displays data as a percentage of a whole

 

Template for Base R Graphics

Start with the graphic function. Inside the parentheses, specify the name of the data points to graph, and add customization parameters separated by commas.

Example: barplot(NameOfDataset$ColumnName, main = "Title of Graph", xlab = "X-axis Name", ylab = "Y-axis Name")

 

Customization Functions

To customize your graphs, here are some of the most common base R functions:

  • Add a graph title: main = "Title of Graph"
  • Add x-axis label: xlab = "X-axis Name"
  • Add y-axis label: ylab = "Y-axis Name"
  • Rotate the label horizontal to the axis (Label of Axis Style): las = 1
  • Rotate the label perpendicular to the axis: las = 2
  • Change the color filling: col = "colorname"
  • Change the outline color: border = "colorname"

Additional customization functions for scatterplots:

  • Change the font size of the axis label: cex.names = ##  (default is 1; increase or decrease value to resize)
  • Change the symbol of scatterplot points: pch = # (Refer to STHDA's chart of plotting symbols)
  • Change outline color of the points: col = "colorname"
  • Change size of the pch symbols: cex = # (default is 1)
  • Change fill color of the open plot symbols (for pch=21-25): bg = "colorname"
  • Add a regression line: abline(lm(y ~ x, data = NameOfDataset), col = "color")
  • Add a LOWESS fit line: lines(lowess(x, y), col ="color")

Additional customization functions for piecharts:

  • Customize the labels of each pie slice: labels = c("LabelName1", "LabelName2", "LabelName3")
  • Adds stripes to each slice: density = # (value of density specifies the number of lines in each slice)
  • Change the angle of stripes: angle = # (value of angle specifies degree of rotation; i.e, 45, 90, 120)

 

Saving Your Graphs

In RStudio:

  1. Use the ‘Export’ function under the 'Plots' tab on the lower right pane to save your graphic in various image formats or PDF (saving your graphs as SVG or PDF files is recommended). 
  2. Change the width and height values to adjust the margin size. 
  3. Be sure to indicate the directory where your file will be saved and give it a ‘File name’.
  4. Click 'Update Preview' to view changes due to the width/height settings before saving.

In the Script Editor:

  1. Write the function for saving your graphic: svg("filename.svg"). Your working directory should have been set to desired file folder; otherwise write out file directory path: svg("C:/Users/username/filename.svg")
  2. Plot your graph with customizations.
  3. Finish ‘developing’ your graph to return the graphic output to your file folder: dev.off()

Some functions to redirect graphic output:

Function Comments
svg("mygraph.svg")

Recommended: Resize without fuzziness or pixelation

pdf("mygraph.pdf")

Recommended: Resize without fuzziness or pixelation

win.metafile("mygraph.wmf")

Ideal for graphs used in Microsoft Word or PowerPoint

png("mygraph.png")

Recommended for webpages

postscript("mygraph.eps")

Suitable for embedding an image in documents, or sending to printers

tiff("mygraph.tiff")

Large file size

jpeg("mygraph.jpg")

Generally for photographs/pixelated images

bmp("mygraph.bmp")

Seldom used outside of Windows operating system