R - Histograms
R - Modern Histograms with ggplot2
Section titled “R - Modern Histograms with ggplot2”A histogram is a vital visualization tool that shows the distribution of a continuous variable. It buckets values into ranges (or “bins”) and displays the frequency of observations in each bin as a bar.
While R’s base graphics include a hist() function for quick plots, the modern standard for creating flexible, publication-quality graphics is the ggplot2 package, a core part of the tidyverse. ggplot2 is based on the “Grammar of Graphics,” a system for building plots layer by layer.
Core ggplot2 Syntax for Histograms
Section titled “Core ggplot2 Syntax for Histograms”The basic syntax for creating a histogram in ggplot2 is:
# First, ensure ggplot2 is installed and loaded# install.packages("ggplot2")library(ggplot2)
ggplot(data = <YOUR_DATA_FRAME>, aes(x = <VARIABLE_TO_PLOT>)) + geom_histogram()Key components:
ggplot(): Initializes the plot. You specify the dataset here.aes(): The aesthetic mapping. You map variables from your data to visual properties of the plot, like the x-axis, y-axis, color, fill, etc.geom_histogram(): The geometric object that tellsggplot2to draw a histogram. This is added with a+.+: The layer operator. You use it to add more elements to your plot, like geoms, labels, themes, etc.
Example: Creating a Basic Histogram
Section titled “Example: Creating a Basic Histogram”Let’s create a histogram of the speed variable from R’s built-in cars dataset. The cars dataset is a data frame, which is the standard input format for ggplot2.
# Load the librarylibrary(ggplot2)
# Create the histogram# We specify the dataset 'cars' and map the 'speed' column to the x-axis.hist_plot <- ggplot(data = cars, aes(x = speed)) + geom_histogram( binwidth = 5, # Control the width of each bin fill = "steelblue", # Set the fill color of the bars color = "white" # Set the border color of the bars ) + labs( # Add labels title = "Distribution of Car Speeds", x = "Speed (mph)", y = "Frequency (Count)", caption = "Data source: R's built-in 'cars' dataset" ) + theme_minimal() # Apply a clean, minimal theme
# Display the plotprint(hist_plot)
# Save the plot to a file# ggsave() is the modern way to save plots.# It automatically detects the format from the extension.ggsave("car_speed_histogram.png", plot = hist_plot, width = 6, height = 4)When you execute the above code, it produces a histogram. The x-axis shows car speed bucketed into intervals of 5 mph. The y-axis shows the number of cars that fall into each speed bucket. The bars are steel-blue with white borders, and the plot has clear titles and axis labels. The ggsave() command will create a file named car_speed_histogram.png in your working directory.
Advanced Customization
Section titled “Advanced Customization”The power of ggplot2 lies in its customizability. You can easily modify aesthetics, scales, and coordinates.
Adjusting Axes and Faceting
Section titled “Adjusting Axes and Faceting”Let’s use the mpg dataset to create a more complex plot. We will look at the distribution of highway miles per gallon (hwy) and split the view by the car’s class (class).
# Load ggplot2 if not already loadedlibrary(ggplot2)
# Create faceted histogramsfacet_plot <- ggplot(data = mpg, aes(x = hwy)) + geom_histogram(binwidth = 2, fill = "#4C72B0", color = "white") +
# facet_wrap creates a separate plot for each category in 'class' facet_wrap(~ class, nrow = 2) +
# coord_cartesian is the best way to zoom without removing data coord_cartesian(xlim = c(10, 50)) +
labs( title = "Highway MPG Distribution by Vehicle Class", x = "Highway Miles Per Gallon (MPG)", y = "Count" ) + theme_light()
print(facet_plot)This code generates a grid of small histograms, one for each vehicle class (e.g., ‘suv’, ‘compact’, ‘pickup’). This makes it incredibly easy to compare the MPG distributions across different categories. All plots share the same x and y axes for consistent comparison.
Best Practices for Histograms
Section titled “Best Practices for Histograms”- Experiment with
binwidth: The number of bins can significantly change the interpretation of a histogram. Try several values to find the one that best reveals the underlying data structure. - Use
facet_wrap()for comparisons: When you want to compare distributions across different groups, faceting is far more effective than trying to overlay multiple histograms. - Label Everything: Always provide a descriptive title, axis labels, and a source caption.
labs()makes this easy. - Consider Accessibility: Use color palettes that are friendly to those with color vision deficiency. Packages like
viridisoffer excellent options.