Plots With R
Ggplot2 ggplot2 is a R package dedicated to data visualization. It can greatly improve the quality and aesthetics of your graphics, and will make you much more efficient in creating them. Ggplot2 allows to build almost any type of chart. The plot function in R isn’t a single defined function but a placeholder for a family of related functions. The exact function being called will depend upon the parameters used. At its simplest, plot function simply plots two vectors against each other.
Combining Plots. R makes it easy to combine multiple plots into one overall graph, using either the par( ) or layout( ) function. With the par( ) function, you can include the option mfrow=c(nrows, ncols) to create a matrix of nrows x ncols plots that are filled in by row.
This is the first post of a series that will look at how to create graphics in R using the plot function from the base package. There are of course other packages to make cool graphs in R (like ggplot2
or lattice
), but so far plot always gave me satisfaction.
In this post we will see how to add information in basic scatterplots, how to draw a legend and finally how to add regression lines.
Data simulation
Adding colors
First plot adding colors for the different treatments, one way to do this is to pass a vector of colors to the col argument in the plot function.
Here is the plot:
Change plotting symbols
R Plot Points
We can also create a vector of plotting symbols to represent data from the two different sites, the different plotting symbols available can be seen here.
Here is the plot:
Add a legend to the graph
Now we should add a legend to the graph:
Here is the plot:
The first argument to legend
is basically its position in the graph, then comes the text of the legend. Optionally one may also specify the colors, plotting symbols etc … of the legend symbol. Have a look at ?legend
for more options.
We can also add a legend outside of the graph by setting xpd=TRUE
and by specifying the x and y coordinates of the legend.
Here is the plot:
Add regression lines
The last thing we might want to add are regression lines
Here is the plot:
Make Plots With R
There is a whole bunch of function to draw elements within the plotting area, a few examples are: points
, lines
, rect
, text
. They are handy in many situations and are very similar of use.
Reading Line Plots With Fractions
That’s it for this basic post, next times we’ll see how to control axis labels and tick marks.