Monday, April 22, 2013

ggplot Style in Classic R Plots

ggplot is a highly acclaimed R package for plotting. I have had very little experience with the library because I've mostly memorized all the quirks of normal R plots. I like the ggplot default style though, so I thought write down how to replicate it in R plots. The distinctive feature of ggplot is the gray rectangle and white grid lines. This may be replicated like so:


#set-up plot coordinate system.
plot(0,0, xlim=c(0,10), ylim=c(0,10), xlab="X", ylab="Y")
#cover up plot with rectangle
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "dark gray")
#now plot the grid
grid(col="white", lty=1)
#now plot data with specific plot type
lines(...)
points(...)
#make sure to put the "add=T" to prevent
#hist from replacing the plot.
hist(..., add=T)
view raw gistfile1.r hosted with ❤ by GitHub

Here's an example



Here's the code to generate that plot:
#set-up plot to be default blogger size. Most computer plots are 90 resolution. Print is about 250
png("ggplot.png", width=400, height=225, res=90)
#Use LaTeX sans font and dark gray annotations. Cut out x-axis label and shrink margins.
par(family="LMSans10", fg="dark gray", mar=c(3,4,1,1))
#set-up plot margins and axis-lables
plot(0,0, xlim=c(-5,5), ylim=c(0,0.5), xlab="", ylab="P(x)")
#code from above
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "dark gray")
grid(col="white", lty=1)
#plot gaussian with color specified and width set at 2
lines(seq(-5,5,0.01), dnorm(seq(-5,5,0.01)), col="black", lwd=2)
graphics.off()
view raw gistfile1.r hosted with ❤ by GitHub

If you ever dislike that extra space that extends the plot region, it may be removed by adding xaxs="i" to par or plot.

No comments:

Post a Comment