We will now be creating histograms in R. The code to create a histogram is the following:

hist(data, main="Title", xlab="x-axis label")

data is the vector that includes the data.

Example:

df <- read.csv('Data/NHANES.csv')
head(df$Height)
## [1] 164.7 164.7 164.7 105.4 168.4 133.1
hist(df$Height, main='Height in the U.S.', xlab='Height (cm)')

Change number of bins

We can easily change the number of bins in a histogram by setting breaks= argument inside hist() and specify the number of bins afterwards:

  1. Number of bins = 5
hist(df$Height, main='Height in the U.S.', xlab='Height (cm)', breaks=5)

  1. Number of bins = 20
hist(df$Height, main='Height in the U.S.', xlab='Height (cm)', breaks=20)

Change color

Same as in the previous visuals, we can change the color by setting col= argument:

hist(df$Height, main='Height in the U.S.', xlab='Height (cm)', breaks=20, col='lawngreen')

©2021 by Daiki Tagami. All rights reserved.