Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R hist() Function - Drawing Histograms

R hist() Function - Drawing Histograms

R Language Examples R Language Examples

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:

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 R Language Examples