[R] ggplot2 Histogram with density curve

Brian Diggs diggsb at ohsu.edu
Fri Jun 10 01:04:07 CEST 2011


On 6/7/2011 8:08 AM, wwreith wrote:
> I am learning ggplot2 commands and I have figured out how to create
> histograms and density curves but I am not sure how to add a density curve
> on top of a histogram.
>
> Here are the two graphs that I created.
>
> ## Histogram
> t<-rnorm(500)
> w<-qplot(t, main="Normal Random Sample", fill=I("blue"), colour=I("black"),
> geom="histogram")
> w
>
> ##Density Curve
> t<-rnorm(500)
> r<-qplot(t, main="Normal Random Sample", colour=I("black"), geom="density",
> adjust=4)
> r
>

# First, ggplot2 works with data.frame's as its input
DF <- data.frame(t=rnorm(500))

# Convert the two graphs from gplot to ggplot syntax
w <- ggplot(DF, aes(x=t)) +
	geom_histogram(fill="blue", colour="black") +
	opts(title="Normal Random Sample")

r <- ggplot(DF, aes(x=t)) +
	geom_density(colour="black", adjust=4) +
	opts(title="Normal Random Sample")

# Now with the layer specifications, it is easy to combine

ggplot(DF, aes(x=t)) +
	geom_histogram(fill="blue", colour="black") +
	geom_density(colour="black", adjust=4) +
	opts(title="Normal Random Sample")

# That was probably not what you want since the histogram is in
# counts and the density curve is in density.  Put them both on the
# same scale (density)

ggplot(DF, aes(x=t)) +
	geom_histogram(aes(y=..density..), fill="blue", colour="black")+
	geom_density(colour="black", adjust=4) +
	opts(title="Normal Random Sample")

# If you want it on the count scale, that is trickier and requires
# knowing (setting) the binwidth and keeping that value in sync in
# two places.
# In this example, the binwidth is 0.2 (set in geom_histogram and also
# used in the aes of geom_density).

ggplot(DF, aes(x=t)) +
	geom_histogram(fill="blue", colour="black", binwidth=0.2) +
	geom_density(aes(y=0.2*..count..), colour="black", adjust=4) +
	opts(title="Normal Random Sample")



-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list