Friday, July 26, 2013

ggplot2 with Noam Ross theme

When I first saw Noam Ross' blog post "The null model for age effects with overdispersed infection", I immediately liked the look of his ggplot2 graphs. I was even more delighted when I discovered that he has made his theme available on github. Even though I am all into rCharts, I still love a beautiful publication quality R graphic.

Below is some code to combine Noam Ross' theme with autoplot.zoo which makes plotting xts/zoo objects with ggplot2 easy.

require(ggplot2)
require(grid)
require(RColorBrewer)
require(quantmod)

# get closing values for S&P 500 from Yahoo! Finance
sp500 <- getSymbols("^GSPC", auto.assign = FALSE)[, 4]

sp500$ma <- runMean(sp500, n = 200)

colnames(sp500) <- c("S&P500", "200d Mov Avg")

# get noam ross ggplot2 theme from github
source("https://raw.github.com/noamross/noamtools/master/R/theme_nr.R")
# for some reason on my computer panel.background still shows up gray this
# fixes it but might not be necessary for others
theme_nr <- theme_nr() + theme(panel.background = element_rect(fill = "white")) +
theme(plot.title = element_text(size = rel(2), hjust = -0.05, vjust = -0.3)) +
theme(plot.margin = unit(c(1, 1, 2, 1), "cm"))

autoplot(sp500, facets = NULL) + theme_nr + theme(legend.position = "none") +
scale_colour_manual(values = brewer.pal("Blues", n = 9)[c(6, 3)]) + geom_line(size = 1.15) +
xlab(NULL) + ggtitle("S&P 500 (ggplot2 theme by Noam Ross)")

It isn’t perfect, but I think it offers a very nice starting point.  Using ggplot2 directly would have allowed us more control over the bothersome details.


Rplot

3 comments:

  1. It did not work

    > source("https://raw.github.com/noamross/noamtools/master/R/theme_nr.R")

    Error in file(filename, "r", encoding = encoding) :

    cannot open the connection

    In addition: Warning message:

    In file(filename, "r", encoding = encoding) : unsupported URL scheme

    ReplyDelete
  2. Thanks for this great post. Unfortunately I also ran into the same problem.

    ReplyDelete
  3. try this

    devtools::source_url("https://raw.github.com/noamross/noamtools/master/R/theme_nr.R")

    See http://christophergandrud.blogspot.com/2012/07/sourcing-code-from-github.html for a better description.

    ReplyDelete