Saturday, December 8, 2012

R: Replicate plot with ggplot2 (part 2) histogram, emprtical curve, normal density curve

The first one is to replicate the scatter plot here. This part is to replicat the plot of histogram.

The original UCLA ATS like is: http://www.ats.ucla.edu/stat/r/gbe/histogram.htm.

In ggplot2, geom_histogram is used to draw histogram.

The data is:
set.seed(121343)
x=rnorm(100)
u <- as.data.frame(x)
view raw gistfile1.txt hosted with ❤ by GitHub

The first one is histogram with black fill:

ggplot(u)+geom_histogram(aes(x=u$x), binwidth=.5, colour="black", fill="white")
view raw gistfile1.r hosted with ❤ by GitHub
The output graph is:

ggplot2 has more choice that you can fill in the color by the counts in each bin. like

ggplot(u)+geom_histogram(aes(x=u$x, , fill=..count..), binwidth=.5, colour="black")
view raw gistfile1.r hosted with ❤ by GitHub

Next is to change the binwidth. In ggplot2 this can be done by binwidth or by breaks. Here is shown by binwidth:

ggplot(u)+geom_histogram(aes(x=u$x), binwidth=.2)
view raw gistfile1.r hosted with ❤ by GitHub

Next is to change from frequency to density(percentage in fact). This can be done by assigning y to be ..density.. in ggplot2:

ggplot(u)+geom_histogram(aes(x=u$x, y=..density..), binwidth=1)
view raw gistfile1.r hosted with ❤ by GitHub


Then is to add normal density and empirical curve in the plot.

First is the empirical curve:

ggplot(u)+geom_histogram(aes(x=u$x, y=..density..), binwidth=.2)+geom_density(aes(x=u$x), colour="red")
view raw gistfile1.r hosted with ❤ by GitHub

Next is the Normal density with mean and std are from the generated data:

ggplot(u)+geom_histogram(aes(x=u$x, y=..density..), binwidth=.2)+stat_function(fun=dnorm, args=list(mean=mean(x), sd=sd(x)), colour="red")+labs(title="Histogram with Density", y="Percentile")
view raw gistfile1.r hosted with ❤ by GitHub

The last one is to add the counts on top of each bin. I did not figure out how to do it. It should be easy by adding text. But unitl now my process has not reached there.

No comments:

Post a Comment