Legends and Dates in R plots
Posted: December 5th, 2011 | Author: Alex Braunstein | Filed under: Uncategorized | 2 Comments »After looking up how to create a legend using ?legend and searching the R forums for the 86586586th time, I’ve decided to write my own post with a few examples and tricks I’ve picked up. I also provide example code for using dates as an x-axis.
I do most of my heavy computation in Python, leaving R for primarily making pretty plots, exploratory data analysis (EDA) when I first get my hands on a data set, and using my favorite R packages/functions that I’ll never implement on my own (ie Random Forests, CART, SVM). Below is an example plot, with two sets of numbers, a legend, and dates on the axis. Hopefully this is more helpful than the R documentation.
len = 43
vals = rnorm(len,0,1)
vals2 = rnorm(len,0,.5)
# pick an initial date in form YYYYMMDD, then generate a years worth of weekly dates
date = 20110201
mydates<-as.Date(as.character(date),"%Y%m%d")
for(i in 1:52){ #
mydates = c(mydates,mydates[length(mydates)]+7)
}
# rename something shorter
x=mydates[2:(len+1)]
# set graphical parameters and plot both random normals, use xaxt="n" to eliminate the x-axis
par(mfrow=c(1,1))
plot(vals,type="l",col="blue",xaxt="n",ylab="y axis label",xlab="",main="Plot Title")
lines(vals2,col="red")
# add back an x-axis with dates, las and cex.axis set direction and size of dates
axis(1, at=1:len,x,las=2,cex.axis=.9)
# add a legend, lwd sets line width, you can use x,y coordinates instead of "bottomleft"
legend("bottomleft", c("thing1","thing2"), col = c("blue", "red"), lwd = 1, title="legend title")
This is the first legend advice that clearly tells you how to put the lines in. Thanks
This has helped me to plot the scatterplot with proper legend. Thanks