Histogram with auto binning in ggplot2

Histograms (with auto binning)

Again, we will use the mtcars dataset and use the fields in that to produce the chart, as we are doing this there is nothing to do on the data preparation side. That leaves us to have fun with the plot.

Building the Histogram with auto binning

I set up the plot, as per below:

1
2
library(ggplot2)
theme_set(theme_classic())

I import the ggplot2 library and set my chart theme to a classic theme. The process next is to create the histogram plot and feed in the relevant data:

1
plot <- ggplot(mpg, aes(displ)) + scale_fill_brewer(palette = "Blues")

I create a plot placeholder in memory so I can reuse this plot again and again in memory. This sets the aes layer equal to the displacement metric in the mtcars data frame. I then use the scale_fill_brewer command and select the palette to the Blues palette. A list of palettes can be found here.

The next section uses the geom_histogram() geometry to force this to be a histogram:

1
2
3
4
5
6
plot + geom_histogram(aes(fill=class),
                   binwidth = .1,
                   col="black",
                   size=.1) +
  labs(title="Histogram with Auto Binning",
       caption="Produced by Gary Hutson") + xlab("Displacement")

The histogram uses the class of vehicle as the histogram fill, the binwidth is the width of the bins required, the colour is equal to black and the size is stipulated here. All that I then do is add the data labels to it and you have a lovely looking histogram built. This can be applied to any dataset. The output is as below:

Specifying binning values

The script can be simply changed in the histogram layer by adding the bins parameter:

1
2
3
4
5
6
plot + geom_histogram(aes(fill=class),
                   bins=5,
                   col="black",
                   size=.1) +
  labs(title="Histogram with Auto Binning",
       caption="Produced by Gary Hutson") + xlab("Displacement")

This has now changed the number of bins to 5 and the scale of the y axis has increased.

This post appears on R-Bloggers – please check out all the other cool blogs featured on this site.
One comment Add yours

Leave a Reply

Your email address will not be published. Required fields are marked *