Sunday, December 9, 2012

R: Replicate plot with ggplot2 (part 4) bar chart

The original plot from UCLA ATS is here. Here the same plot is done in package ggplot2.

Let's read in the data:
hsb2 <- read.table('http://www.ats.ucla.edu/stat/r/modules/hsb2.csv', header=T, sep=",")
attach(hsb2)
view raw gistfile1.r hosted with ❤ by GitHub
The bar chart here is to show how many observations for each level of ses(=1, 2 and 3 separately, will be replaced by "low", "median" and "high" separately).

The first plot is the plain bar chart:

# barchart, change the fill to white, and colour to blue
ggplot(hsb2)+geom_bar(aes(factor(ses)), fill="white", colour="blue")
view raw gistfile1.r hosted with ❤ by GitHub

The second one is to replace the original value of ses by "low", "median" and "high" separately:

# change the labels of factor ses
hsb2$ses=factor(hsb2$ses, labels=c("low", "median", "high"))
ggplot(hsb2)+geom_bar(aes(factor(ses)), fill="white", colour="blue")
view raw gistfile1.r hosted with ❤ by GitHub

The third one is to change the width of the bin.

# change the width
ggplot(hsb2)+geom_bar(aes(factor(ses)), width=.5, fill="white", colour="blue")
view raw gistfile1.r hosted with ❤ by GitHub

The forth is to group the data by female first, and then bin on each level of female(0 or 1). This is stacked plot. From the plot it is not easy to figure out which is higher. So we need to plot it separately as is shown in the fifth graph.

# stacked bar chart: female as bin, and ses as bar. But this is not easy to compare directly.
# for example, if you need to compare counts of median in male and female(green part), it is not easy here
ggplot(hsb2)+geom_bar(aes(factor(female), fill=ses), width=.5, colour="blue")
view raw gistfile1.r hosted with ❤ by GitHub

The fifth one is plot bar chart at each level of female. That is, plot two bar chart for ses at 0 and 1 level of females separately.

# ggplot2 provide faceting, which help to make the data clearer
ggplot(hsb2)+geom_bar(aes(factor(ses), fill=ses), width=.8)+facet_wrap(~female)
view raw gistfile1.r hosted with ❤ by GitHub


No comments:

Post a Comment