R boxplot() Function - Drawing Box Plots
The R boxplot() function is used to draw box plots, showing the distribution characteristics and outliers of data.
A box plot shows the five-number summary of the data (minimum, Q1, median, Q3, maximum) as well as outliers.
The syntax of the boxplot() function is as follows:
boxplot(x, horizontal = FALSE, col = NULL,
main = "", xlab = "", ylab = "")
Parameter Description:
-
x A numeric vector or a formula (such as value ~ group).
Example
Score data for multiple classes
class_a
<-
c
(
78
,
82
,
85
,
88
,
90
,
75
,
80
,
86
,
92
,
84
)
class_b
<-
c
(
72
,
75
,
78
,
76
,
80
,
70
,
74
,
77
,
79
,
73
)
class_c
<-
c
(
85
,
88
,
90
,
92
,
95
,
80
,
87
,
89
,
91
,
86
)
Draw box plot
boxplot
(
class_a, class_b, class_c,
names
=
c
(
"Class A"
,
"Class B"
,
"Class C"
)
,
main
=
"Comparison of Score Distribution by Class"
,
xlab
=
"Class"
,
ylab
=
"Score"
,
col
=
c
(
"skyblue"
,
"lightgreen"
,
"coral"
)
)
Running the above code displays a box plot comparison of the scores of the three classes.
boxplot() is more convenient for grouped data when using the formula form:
Example
Using the formula form
scores
<-
c
(
class_a, class_b, class_c
)
groups
<-
rep
(
c
(
"Class A"
,
"Class B"
,
"Class C"
)
, each
=
10
)
boxplot
(
scores ~ groups,
main
=
"Box Plot of Scores by Class"
,
col
=
rainbow
(
3
)
)
R Language Examples