5 Chart: Histogram

5.1 Overview

This section covers how to make histograms.

5.3 Simple examples

Whoa whoa whoa! Much simpler please!

Let’s use a very simple dataset:

5.3.1 Histogram using base R

For the Base R histogram, it’s advantages are in it’s ease to setup. In truth, all you need to plot the data x in question is hist(x), but we included a little color and a title to make it more presentable.

Full documentation on hist() can be found here

5.3.2 Histogram using ggplot2

The ggplot version is a little more complicated on the surface, but you get more power and control as a result. Note: as shown above, ggplot expects a dataframe, so if you are getting an error where “R doesn’t know what to do” like this:

ggplot dataframe error

ggplot dataframe error

make sure you are using a dataframe.

5.4 Theory

Generally speaking, the histogram is one of many options for displaying continuous data.

The histogram is clear and quick to make. Histograms are relatively self-explanatory: they show your data’s empirical distribution within a set of intervals. Histograms can be employed on raw data to quickly show the distribution without much manipulation. Use a histogram to get a basic sense of the distribution with minimal processing necessary.

  • For more info about histograms and continuous variables, check out Chapter 3 of the textbook.

5.5 Types of histograms

Use a histogram to show the distribution of one continuous variable. The y-scale can be represented in a variety of ways to express different results:

5.5.1 Frequency or count

y = number of values that fall in each bin

5.5.2 Relative frequency historgram

y = number of values that fall in each bin / total number of values

5.5.3 Cumulative frequency histogram

y = total number of values <= (or <) right boundary of bin

5.5.4 Density

y = relative frequency / binwidth

5.6 Parameters

5.6.3 Bin alignment

Make sure the axes reflect the true boundaries of the histogram. You can use boundary to specify the endpoint of any bin or center to specify the center of any bin. ggplot2 will be able to calculate where to place the rest of the bins (Also, notice that when the boundary was changed, the number of bins got smaller by one. This is because by default the bins are centered and go over/under the range of the data.)

Note: Don’t use both boundary and center for bin alignment. Just pick one.

5.7 Interactive histograms with ggvis

The ggvis package is not currently in development, but does certain things very well, such as adjusting parameters of a histogram interactively while coding.

Since images cannot be shared by knitting (as with other packages, such as plotly), we present the code here, but not the output. To try them out, copy and paste into an R session.

5.8 External resources







with