Last active
August 29, 2015 14:01
-
-
Save mwfrost/5535e0fb6dab0bca2f11 to your computer and use it in GitHub Desktop.
ggplot2 code for generating grid plots for proportional comparison
This file contains hidden or 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
| # Generate test data | |
| chicdat <- diamonds | |
| # calculate percentages by the categorical variable | |
| chicdat$pct.full <- 1/nrow(chicdat) | |
| catpct <- ddply(chicdat, .(cut), summarize, pct=sum(pct.full)) | |
| catpct$rollpct <- cumsum(catpct$pct) | |
| # Box Precision: what's the smallest portion that each box represents? | |
| # A 400-box grid can show 0.25%, for example, so 400 boxes is the default | |
| boxcount <- 400 | |
| boxcols <- 10 | |
| boxrows <- boxcount / boxcols | |
| boxes <- expand.grid(boxcol = seq(1:boxcols), boxrow=seq(1:boxrows) ) | |
| boxes$boxpct <- 1/boxcount | |
| boxes$boxbottom <- cumsum(boxes$boxpct) - boxes$boxpct | |
| boxes$boxtop <- cumsum(boxes$boxpct) | |
| ddply(chicdat, .(cut), summarize, sum(pct.full)) | |
| boxes$boxcat <- cut(boxes$boxbottom, c(-0.01, catpct$rollpct), catpct$cut) | |
| # Plot the graph | |
| ggplot(boxes) + geom_tile(aes(x=boxcol, y=boxrow, fill=boxcat) ,color='white') + | |
| theme( | |
| plot.background = element_blank() | |
| ,panel.grid.major = element_blank() | |
| ,panel.grid.minor = element_blank() | |
| ,panel.border = element_blank() | |
| # ,panel.background = element_blank() | |
| ,axis.ticks = element_blank() | |
| ,axis.text = element_blank() | |
| ,axis.title = element_blank() | |
| ) + | |
| scale_x_continuous(expand = c(0,0)) + | |
| scale_y_reverse(expand = c(0,0)) + | |
| coord_fixed(ratio = 1) + | |
| scale_fill_brewer(type='qual') + | |
| guides(fill = guide_legend(title='Category')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment