Created
August 9, 2013 10:11
-
-
Save aaronsaunders/6192604 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment