[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.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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)< o:p>
library(grid)
library(reshape2)< o:p>
m <- acast(melt(unclass(Titanic)), Class ~ Age + Sex, sum)< o:p>
names(dimnames(m)) <- c(“Class”, “Age_Sex”)< o:p>
df <- melt(unclass(chisq.test(m)$res), value.name = “residuals”)< o:p>
g1 <- ggplot(df, aes(x = Class, y = Age_Sex)) +< o:p>
geom_tile(aes(fill = residuals)) +< o:p>
scale_fill_gradientn(colours=c(“blue”,“white”,“red”)) +< o:p>
theme_bw()< o:p>
m <- acast(melt(unclass(Titanic)), Class~Age+Sex,< o:p>
function(x) {x[2] / sum(x)})< o:p>
names(dimnames(m)) <- c(“Class”,“Age_Sex”)< o:p>
df <- melt(m, value.name = “survived”)< o:p>
g2 <- ggplot(df, aes(x = Class, y = Age_Sex)) +< o:p>
geom_tile(aes(fill = survived)) +< o:p>
scale_fill_gradient(low = “blue”, high = “red”)+theme_bw()< o:p>
grid.newpage()< o:p>
pushViewport(viewport(layout = grid.layout(1, 2)))< o:p>
print(g1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))< o:p>
print(g2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))< o:p>
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.