You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中创建带阴影的直方图?Base R已实现但ggplot2遇阻

How to Create Hatched Histograms in ggplot2 (Like Base R's 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’s density argument)
  • pattern_angle: Sets the rotation of the pattern lines (matches base R’s angle argument)
  • pattern_fill: Color of the pattern lines
  • fill: 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:02:38