Histograms in R
In the fields of statistics and data analysis, histograms are one of the most fundamental and widely applied graphical tools. They are primarily used to display the distribution of continuous data, reflecting the frequency or density of data occurrences within specific intervals through the height of rectangular bars. Unlike simple bar charts, the horizontal axis of a histogram represents the boundaries of numerical intervals, with adjacent rectangular bars connected closely to collectively depict the overall shape, central tendency, and dispersion of the data. For beginners, mastering the method of drawing histograms in R is the first step toward understanding the characteristics of data distributions.
In R, the core function for drawing histograms is hist(). This function can automatically calculate the binning process of the data and generate the corresponding graph. Its basic syntax structure is as follows:
hist(x, breaks = "FD", col = rgb(0, 0, 1, 0.5), main = "Histogram of Data Distribution",
xlab = "Numerical Variable", ylab = "Frequency", ...)
In this function, the x parameter specifies the numerical vector to be plotted; the breaks parameter controls the number or method of binning, defaulting to the "FD" (Freedman-Diaconis) rule to automatically determine the optimal number of bins; the col parameter sets the color of the rectangular bars; and main, xlab, and ylab are used to customize the main title and axis labels of the chart.
Custom Binning Strategies and Frequency Density
Although the hist() function possesses the ability to automatically calculate binning, researchers often need to adjust the binning strategy according to specific business requirements in practical analysis. For example, when data distributions are extremely skewed or certain specific intervals need to be highlighted, manually specifying the breaks parameter becomes particularly important. R supports various binning methods, including a fixed number of bins, fixed width, or boundaries based on theoretical distributions.
Furthermore, to more accurately compare the distribution shapes of different datasets, it is generally recommended to switch the chart type from "frequency" to "density". This can be achieved by setting the freq = FALSE parameter. At this point, the vertical axis represents probability density rather than the sum of counts, and the sum of areas of all histograms will equal 1, thereby eliminating the interference of sample size differences on the intuitive comparison of graphs.
Practical Example: From Raw Data to Visualization Results
To demonstrate the above concepts, we first create a vector containing simulated data and then gradually show how to draw histograms of different styles. Suppose we have a set of simulated normal distribution data data:
# Generate a sample dataset with a mean of 50 and standard deviation of 10
set.seed(123)
data <- rnorm(100, mean = 50, sd = 10)
# Draw the default frequency histogram
hist(data, breaks = "FD", col = "steelblue", main = "Default Binning Histogram",
xlab = "Value", ylab = "Frequency")
In the code above, breaks = "FD" allows R to automatically calculate the number of bins suitable for this sample size, and col = "steelblue" sets the classic steel blue color scheme. The execution result will display a typical bell-shaped distribution curve.
Next, we can attempt to customize the bin width to observe changes:
# Draw a histogram with fixed bin width, one bin per 5 units
hist(data, breaks = seq(min(data), max(data), by = 5),
col = "lightgreen", main = "Fixed Width Histogram",
xlab = "Value", ylab = "Frequency")
Here, we explicitly define a sequence from the minimum to the maximum value with a step size of 5. This approach allows us to obtain clearer graphical comparison effects when the data range is known and standardized display is required.
Advanced Applications: Multivariate Distributions and Density Overlays
When facing multiple datasets or requiring more refined statistical analysis, R provides flexible extension features. For example, we can simultaneously plot two datasets with different distributions for comparison, or overlay a Kernel Density Estimate (KDE) curve above the histogram to smoothly display distribution trends.
The following code demonstrates how to overlay density lines in a single graph:
# Generate a second dataset
data2 <- rnorm(100, mean = 60, sd = 15)
# Create the graphical framework
plot(hist(data, col = "blue", main = "Comparison of Two Datasets"),
xlab = "Value", ylab = "Frequency")
# Add density lines above the existing histogram
lines(density(data), col = "red", lwd = 2)
lines(density(data2), col = "purple", lwd = 2)
legend("topright", legend = c("Dataset A", "Dataset B"),
col = c("blue", "purple"), lwd = 2)
This code first draws the histogram of the first dataset as a background, and then uses the lines() function to overlay density curves for both datasets. Through color differentiation and legend explanation, readers can intuitively perceive the significant differences in mean and variance between the two datasets. This combination graph method is extremely common in academic research and business reports, greatly enhancing the efficiency of information transmission.
Mastering histogram drawing techniques in R not only helps in quickly generating statistical charts but also cultivates keen insight into data distributions. From basic frequency statistics to complex density overlays, every operation contains rich analytical thinking, worth every R learner to explore and practice deeply.