R boxplot() Function - Drawing Box Plots

R 语言实例R Language Examples

The R boxplot() function is used to draw box plots, showing the distribution characteristics and outliers of data.

The box plot displays the five-number summary of 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:

  • xA numeric vector or 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 distributions across classes,
        xlab = Class,
        ylab = Score,
        col = c("skyblue", "lightgreen", "coral"))

Running the above code will display a box plot comparison of scores for the three classes.

Using the formula form of boxplot() is more convenient for grouped data:

Example

# Using 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 plots of scores by class,
        col = rainbow(3))

R 语言实例R Language Examples

Other Extensions