Visualizing tables in ggplot2

May 5, 2012

(This article was first published on R snippets, and kindly contributed to R-bloggers)

Recently I wanted to recreate  assocplot  using  ggplot2. In the end I propose a simple way to visualize data arranged two-way tables using geom_tile.

I used Titanic data set as an example combining age and sex dimensions to get two-way data.

I plot residuals of Chi-squared test (like in assocplot) on the left and probability of survival on the right. A nice feature of geom_tile is that nicely highlights missing data (children were not crew members). Here is a code generating the plots:

m <- acast(melt(unclass(Titanic)), Class ~ Age + Sex, sum)
names(dimnames(m)) <- c(“Class”, “Age_Sex”)
df <- melt(unclass(chisq.test(m)$res), = “residuals”)
g1 <- ggplot(df, aes(x = Class, y = Age_Sex)) +
  geom_tile(aes(fill = residuals)) +
  scale_fill_gradientn(colours=c(“blue”,“white”,“red”)) +
m <- acast(melt(unclass(Titanic)), Class~Age+Sex,
           function(x) {x[2] / sum(x)})
names(dimnames(m)) <- c(“Class”,“Age_Sex”)
df <- melt(m, = “survived”)
g2 <- ggplot(df, aes(x = Class, y = Age_Sex)) +
  geom_tile(aes(fill = survived)) +
  scale_fill_gradient(low = “blue”, high = “red”)+theme_bw()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(g1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(g2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

And the result:

To leave a comment for the author, please follow the link and comment on his blog: R snippets. offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.