Plotting distributions (ggplot2)
Solution
This sample data will be used for the examples below:
The function is supposed make the same graphs as ggplot
, but with a simpler syntax. However, in practice, it’s often easier to just use ggplot
because the options for qplot
can be more confusing to use.
## Basic histogram from the vector "rating". Each bin is .5 wide.
## These both result in the same output:
ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5)
# qplot(dat$rating, binwidth=.5)
# Draw with black outline, white fill
ggplot(dat, aes(x=rating)) +
geom_histogram(binwidth=.5, colour="black", fill="white")
# Density curve
# Histogram overlaid with kernel density curve
ggplot(dat, aes(x=rating)) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.5,
colour="black", fill="white") +
geom_density(alpha=.2, fill="#FF6666") # Overlay with transparent density plot
Add a line for the mean:
# Overlaid histograms
ggplot(dat, aes(x=rating, fill=cond)) +
geom_histogram(binwidth=.5, alpha=.5, position="identity")
# Interleaved histograms
ggplot(dat, aes(x=rating, fill=cond)) +
geom_histogram(binwidth=.5, position="dodge")
ggplot(dat, aes(x=rating, colour=cond)) + geom_density()
# Density plots with semi-transparent fill
ggplot(dat, aes(x=rating, fill=cond)) + geom_density(alpha=.3)
Add lines for each mean requires first creating a separate data frame with the means:
Using facets:
ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5, colour="black", fill="white") +
facet_grid(cond ~ .)
# With mean lines, using cdat from above
ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5, colour="black", fill="white") +
facet_grid(cond ~ .) +
geom_vline(data=cdat, aes(xintercept=rating.mean),
linetype="dashed", size=1, colour="red")
See ) for more details.
It’s also possible to add the mean by using stat_summary
.
# Add a diamond at the mean, and make it larger
stat_summary(fun.y=mean, geom="point", shape=5, size=4)