ggplot2 theme in base R graphics

This possibly pointless exercise aims at reproducing the default theme of ggplot2 graphs with base graphics. It could be useful to obtain a consistent style in a document comprising both types of graphs.

library(ggplot2)
 
graphics.off()
x <- seq(0, 10, len = 100)
y1 <- jitter(sin(x), 1000)
y2 <- 0.5 * jitter(cos(x), 1000)
 
greyDark <- grey(0.5)
greyLight <- grey(0.9)
myColors <- c("#E41A1C", "#377EB8")
palette(myColors)
 
old.par <- par()
par(cex = 1, bty = "n", fg = greyDark, col.lab = "black", 
  xpd = FALSE, mar = old.par$mar + c(-2, -1, -1, 3),
  mgp = c(1.8, 0.5, 0), col = "black")
 
plot(x, y1, new = TRUE, t = "n") # plots nothing, needed to find the dimensions
 
lims <- par("usr")
# position of the grid sub-divisions
subGrid1 <- axTicks(1) + mean(diff(axTicks(1)))/2 
subGrid2 <- axTicks(2) + mean(diff(axTicks(2)))/2
 
plot(x, y1, col = 1, xlab = "x",  ylab = "value", xaxt = "n",
  yaxt = "n", pch = 16, cex = 0.8, 
  panel.first = {
    rect(lims[1], lims[3], lims[2], lims[4], bord = NA, 
      col = greyLight) # grey background
    segments(axTicks(1), lims[3], axTicks(1), lims[4],
      col = "white" , lwd = 1.2) # main grid
    segments(lims[2], axTicks(2), lims[3], axTicks(2),
      col = "white" , lwd = 1.2)
    segments(subGrid1, lims[3], subGrid1, lims[4],
      col = "white" , lwd = 0.5) # secondary grid
    segments(lims[2], subGrid2, lims[3], subGrid2,
      col = "white" , lwd = 0.5)
    axis(1, lty = "solid", lwd = 1, col = greyDark,
      col.axis = greyDark, tcl = -0.4, cex.axis = 0.8) # axis
    axis(2, lty = "solid", lwd = 1, col = greyDark,
      col.axis = greyDark, las = 1, tcl = -0.4, cex.axis = 0.8)
})
 
par(bty = "o")
box(col = "white", lwd = 3) # draws in white over the axes
# some more plotting as usual
points(x, y2, col = 2, cex = 0.8, pch = 16) 
 
par(xpd = TRUE) # legend is outside
legend(1.1 * max(x), mean(y1), pch = 16, col = 1:2,
  c("one", "two"), bty = "n", title = "variable")
 
title(main = "ggplot theme with base graphics")
 
par(old.par)
 
# and here is the ggplot2 version
df <- melt(data.frame(x = x, one = y1, two = y2), id = "x")
p <- qplot(x, value, data = df,colour = variable,
  main = "ggplot2 (almost) defaults")
p + scale_colour_manual(values = myColors)

:tips:graphics-misc:comparison.png

 
tips/graphics-misc/ggplot2theme_inbase.txt · Last modified: 2008/08/06
 
Recent changes RSS feed R Wiki powered by Driven by DokuWiki and optimized for Firefox Creative Commons License