R hist() Function - Drawing Histograms
The R hist() function is used to draw a histogram, showing the distribution of the data.
A histogram divides the data into several intervals (bins) and shows the frequency or frequency count of data in each interval.
The syntax of the hist() function is as follows:
hist(x, breaks = "Sturges", freq = NULL, col = NULL,
main = paste("Histogram of", xname))
Parameter Description:
-
x A numeric vector.
-
breaks The way intervals are divided: it can be a number (number of intervals), a vector (breakpoint positions), or an algorithm name.
-
freq Whether to show frequency (TRUE) or density (FALSE).
Example
Generate exam score data
set.seed
(
123
)
scores
<-
rnorm
(
200
,
mean
=
70
,
sd
=
10
)
Draw a histogram
hist
(
scores,
main
=
"Exam score distribution"
,
xlab
=
"Score"
,
ylab
=
"Frequency"
,
col
=
"skyblue"
,
border
=
"white"
,
breaks
=
15
)
Add mean and median lines
abline
(
v
=
mean
(
scores
)
,
col
=
"red"
, lwd
=
2
, lty
=
2
)
abline
(
v
=
median
(
scores
)
,
col
=
"blue"
, lwd
=
2
, lty
=
3
)
legend
(
"topright"
,
legend
=
c
(
"Mean"
,
"Median"
)
,
col
=
c
(
"red"
,
"blue"
)
, lty
=
c
(
2
,
3
)
, lwd
=
2
)
Running the above code will display a histogram, with a red mean line and a blue median line.
R Language Examples