Visualizing tables in ggplot2

[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:


library(ggplot2)
library(grid)
library(reshape2)

m <- acast(melt(unclass(Titanic)), Class ~ Age + Sex, sum)
names(dimnames(m)) <- c(“Class”, “Age_Sex”)
df <- melt(unclass(chisq.test(m)$res), value.name = “residuals”)
g1 <- ggplot(df, aes(x = Class, y = Age_Sex)) +
  geom_tile(aes(fill = residuals)) +
  scale_fill_gradientn(colours=c(“blue”,“white”,“red”)) +
  theme_bw()

m <- acast(melt(unclass(Titanic)), Class~Age+Sex,
           function(x) {x[2] / sum(x)})
names(dimnames(m)) <- c(“Class”,“Age_Sex”)
df <- melt(m, value.name = “survived”)
g2 <- ggplot(df, aes(x = Class, y = Age_Sex)) +
  geom_tile(aes(fill = survived)) +
  scale_fill_gradient(low = “blue”, high = “red”)+theme_bw()

grid.newpage()
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 their blog: R snippets.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)