Created
June 2, 2013 16:10
-
-
Save Ram-N/5693965 to your computer and use it in GitHub Desktop.
Plotting UCBerkeley admissions using ggplot2.
See what the different options in ggplot2 do, and how to get your desired graph.
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
rm(list=ls()) | |
library(datasets) | |
library(ggplot2) | |
str(UCBAdmissions) #Table, but ggplot needs data frames | |
ucb <- data.frame(UCBAdmissions) | |
names(ucb) | |
head(ucb) | |
#We Would Like to Create some Barplots | |
p <- ggplot(ucb, aes(x=Gender, y=Freq) ) | |
histg<- geom_bar(stat ="identity") | |
p+histg # All the departments and Admit/Rejects are mushed together | |
#We need to separate it out | |
#First, pull the departments apart | |
p + histg + facet_grid(. ~ Dept) #Accept and Reject still need to be separated out | |
p + histg + facet_grid(. ~ Dept+Admit) # would be nice to color them differently. Use fill for that | |
#Let's use fill | |
p2 <- ggplot(ucb, aes(x=Gender, y=Freq, fill=factor(Admit)) ) | |
p2 + histg + facet_grid(. ~ Dept + Admit) #not good. Because it is difficult to compare same gender | |
#let's try | |
p2 + histg + facet_grid(. ~ Admit+Dept) #This made it worse. The departments are too far apart. | |
#How about | |
p2 + histg + facet_grid(. ~ Dept) #Almost there. But we don't want a stacked barplot | |
#But we want Male Admits and Rejects together for each department. | |
#Notice that X aesthtic, the gender is the closest together. | |
#This means that in our final plot, ADMIT will have to be the x-aesthetic | |
#start again | |
p3 <- ggplot(ucb, aes(x=Admit, y=Freq, fill=factor(Admit)) ) | |
p3 + histg + facet_grid(. ~ Dept+Gender) | |
p3 + histg + facet_grid(. ~ Dept+Gender) + theme(axis.text.x=element_blank()) | |
#Finally! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment