Pretty histograms with ggplot2
@drsimonj here to make pretty histograms with ggplot2!
In this post you’ll learn how to create histograms like this:
Let’s simulate data for a continuous variable
x in a data frame
set.seed(070510) d <- data.frame(x = rnorm(2000)) head(d) > x > 1 1.3681661 > 2 -0.0452337 > 3 0.0290572 > 4 -0.8717429 > 5 0.9565475 > 6 -0.5521690
Create the basic ggplot2 histogram via:
library(ggplot2) ggplot(d, aes(x)) + geom_histogram()
Time to jazz it up with colour! The method I’ll present was motivated by my answer to this StackOverflow question.
We can add colour by exploiting the way that ggplot2 stacks colour for different groups. Specifically, we fill the bars with the same variable (
cut into multiple categories:
ggplot(d, aes(x, fill = cut(x, 100))) + geom_histogram()
Oh, ggplot2 has added a...
Continue reading →