如何在ggplot2中创建带阴影的直方图?Base R已实现但ggplot2遇阻
hist() with density/angle) Great question—using patterned fills instead of solid colors is such a smart call for grayscale printing or when color isn’t feasible. Base R’s hist() makes this straightforward with density and angle parameters, but ggplot2’s default geom_histogram() doesn’t have built-in support for this. Luckily, there’s a clean solution using the ggpattern package, which adds pattern-based fill options to ggplot2 geoms.
Step 1: Install and Load the ggpattern Package
First, install the package if you haven’t already:
install.packages("ggpattern")
Then load it alongside ggplot2:
library(ggplot2) library(ggpattern)
Step 2: Build the Hatched Histogram
Replace geom_histogram() with geom_histogram_pattern(), and use parameters that mirror your base R setup:
pattern: Pick the pattern type (use"stripe"to match base R’s angled shadow lines)pattern_density: Controls how tightly packed the pattern lines are (matches base R’sdensityargument)pattern_angle: Sets the rotation of the pattern lines (matches base R’sangleargument)pattern_fill: Color of the pattern linesfill: Background fill of the bars (set to"white"if you only want the pattern, no solid color)
Here’s the full code that replicates your base R example:
library(ggplot2) library(ggpattern) ggplot(diamonds, aes(carat)) + geom_histogram_pattern( pattern = "stripe", pattern_density = 25, pattern_angle = 60, pattern_fill = "black", fill = "white", color = "black" # Optional: adds bar borders like base R's default ) + theme_bw()
Bonus: Customize the Pattern
You can tweak the look further by trying other patterns like "crosshatch" (intersecting lines), "dot", or "wave". Adjust pattern_density to make lines more/less sparse, or pattern_angle to rotate them to your preferred orientation.
Alternative Without Extra Packages (Advanced)
If you’d rather avoid installing a new package, you could manually draw pattern lines with geom_segment(), but this requires calculating bar positions and heights first—it’s far less efficient than using ggpattern. For most use cases, ggpattern is the simplest, most maintainable solution.
内容的提问来源于stack exchange,提问作者Christoph

