Cite as: Alfonso Garmendia (2016) R for life sciences. Chapter 2: Operations in R. http://personales.upv.es/algarsal/Documentation/Garmendia-R-Tutorial-03_Graphics.html

available in PDF and EPUB

 

 

 


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

 

Written in Rmarkdown, using Rstudio and pandoc.


Basic graphics and data

Basic graphics with one variable

One of the main reasons to use R instead of statistical programs is for its strong graphical capabilities. To see some of these capabilities, write demo(graphics).

Basic graph types are density plots, dot plots, bar charts, line charts, pie charts, box-plots and scatter plots.

Plots in R have two types of commands, high-level commands to create the plot and low-level commands to add things to the plot, once it has been created. These low-level commands will do nothing if there is not an active plot.

Some of the most used low-level commands are:

points () :
Add points
lines() :
Add a line graph
abline () :
Add a straight line
title() :
Add a title
legend() :
Add a legend
text() :
Add a text string at the desired coordinates into a figure.

The main primary command is plot(). Depending the input data, it will do the type of plot that best fit. But of course is possible to change. Looking at the help(plot) page is very advisable before start and take a look into the arguments. Changing for example the type of plot.

################ BASIC GRAPHS ###################
# Define the greenfly vector with 5 values
greenfly <- c(1, 3, 6, 4, 9)
################ POINTS #########################
# Graph the greenfly vector with all defaults
plot(greenfly)
plot of chunk unnamed-chunk-1

plot of chunk unnamed-chunk-1

################ LINES  #########################
# Graph the greenfly vector with a line
plot(greenfly, type = "l")
plot of chunk unnamed-chunk-1

plot of chunk unnamed-chunk-1

################ BARPLOT ########################
# Names for the bars
years <- as.character(1999:2003)
# Graph the greenfly vector with barplot
barplot(greenfly, names.arg = years)