Add more to a histogram in R

Add more to a histogram in R

A histogram is a standard way to present the distribution of a sample of numbers. A basic histogram is useful but it is easy to add more to a histogram in R to produce an even more informative plot. In this article you’ll see how to add a rug and a strip-chart to a basic historgram using simple R commands.

A basic histogram

It is easy to make a histogram using R with the hist() command. For example:

set.seed(123)
x <- norm(n = 50, mean = 10, sd = 1)
hist(x, col = "skyblue")

Produces a histogram resembling this:

Add a rug

A rug plot can be added to more or less any graphic. The rug() command can add the rug to any side of the plot:

  • side = 1 is the bottom axis
  • side = 2 is the left axis

You can alter the colour and width of the rug lines using regular graphical parameters:

rug(x, side = 1, col = "blue")

Adds the rug like so:

Add a strip chart

A strip chart can also be added to any chart via the stripchart() command. However, you also need to specify add = TRUE to the command. Giving a bit of jitter helps to separate out points that are coincident:

stripchart(x,
           method = "jitter",
           pch = 23,
           bg = "pink",
           add = TRUE)

The final plot looks like so:

There are many additional options for the stripchart() command; use help(stripchart) in R to find out more. Look out for other articles in our Tips & Tricks pages.

Comments are closed.