Box Plots in R
Box plots are a powerful tool for visualizing data distribution characteristics in the fields of statistics and data analysis. They not only present the central tendency, dispersion, and outliers of data intuitively but also enable quick comparison of differences between different groups. For beginners learning R language, mastering the creation and interpretation of box plots is a crucial step in conducting Exploratory Data Analysis (EDA).
The core structure of a box plot consists of five key numerical values: minimum value (lower whisker), first quartile (Q1, lower boundary), median (line inside the box), third quartile (Q3, upper boundary), and maximum value (upper whisker). The rectangular box in the middle represents the distribution range of the middle 50% of the data, known as the interquartile range (IQR). The "whiskers" extending upwards and downwards typically extend to data points within a range defined by $1.5 \times$ IQR from Q1 or Q3. Data points falling outside this range are considered outliers and displayed on the plot as individual circles or asterisks.
R provides several functions for creating box plots, among which boxplot() is the most commonly used and feature-rich. This function accepts a numeric vector or multiple data frames as input, flexibly handling single-variable or multi-variable distribution display requirements.
For the case of a single numeric vector, boxplot() is the most direct choice. Below is a simple example demonstrating how to draw a box plot for a set of random data:
# Generate a simulated dataset
set.seed(123)
data <- rnorm(n = 50, mean = 50, sd = 10)
# Draw the basic boxplot
boxplot(data)
After running the code above, R will pop up a window displaying the box plot. By observing the graph, you can immediately see the position of the median, the overall distribution shape of the data, and whether there are obvious outliers present. If the data exhibits skewness, the box will tilt towards one side; if numerous outlying points exist, scattered dots will be visible at the ends of the whiskers.
Multi-variable Comparison and Group Analysis
In practical applications, we often need to compare the distribution situations of different groups of data. The boxplot() function can accept multiple vectors via the varnames parameter (or more commonly in modern R versions through formula interfaces), thereby drawing multiple box plots on a single chart for intuitive inter-group comparison.
Assume we have a set of experimental data recording changes in patient blood pressure under different drug dosages:
# Create a simulated dataframe
df <- data.frame(
group = c(rep("Low", 20), rep("Medium", 20), rep("High", 20)),
bp_change = c(rnorm(n = 20, mean = 5, sd = 10),
rnorm(n = 20, mean = 10, sd = 12),
rnorm(n = 20, mean = 15, sd = 14))
)
# Draw boxplots grouped by category
boxplot(bp_change ~ group, data = df,
main = "Blood Pressure Changes Under Different Drug Dosages",
ylab = "Change in Blood Pressure (mmHg)",
col = c("lightblue", "lightgreen", "lightyellow"))
In this example, we use the formula interface bp_change ~ group to instruct R that 'group' is a categorical variable and 'bp_change' is a numeric variable. By adjusting the col parameter, we can assign different colors to box plots of different groups, making the chart more aesthetically pleasing and easier to distinguish. This visualization method is widely applied in medicine, social sciences, quality control, and other fields because it clearly reveals differences between group means as well as distinctions in variance sizes.
Advanced Customization and Styling Options
Although basic functions are already quite powerful, we usually need further customization of charts for professional reports to meet specific publication or presentation requirements. boxplot() offers a wealth of parameters to control details such as line colors, font size, label positions, etc.
You can use the las parameter to control the direction of labels (e.g., horizontal or vertical), and utilize the width parameter to adjust the width of the box to fit the chart layout. Additionally, combining with the par() function allows setting global borders and background colors for the plotting area. For scenarios requiring precise control over data point display, you can also combine it with the points() function to overlay specific numerical points on top of the box plot so that readers can verify the true magnitude of each outlier.
# Advanced customization example
boxplot(bp_change ~ group, data = df,
las = 1, # Display labels horizontally
width = 0.6, # Box width
col = "steelblue",
border = "black",
main = "Customized Drug Dosage Comparison Chart",
cex.axis = 1.2)
# Optional: Add specific numerical points to the plot
points(df$bp_change, pch = 21, bg = "red")
Through these adjustments, the generated chart not only retains statistical accuracy but also enhances professional visual communication capabilities. Mastering these techniques will help you advance from basic R language operations to producing high-quality technical reports.