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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to