Excel, GraphPad Prism, or other graphical software are sufficient when creating basic graphs, but R packages can extend data visualization capabilities.
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.
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:
Additional customization functions for scatterplots:
Additional customization functions for piecharts:
Saving Your Graphs
In RStudio:
In the Script Editor:
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 |