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

如何在ggplot2的面积图或直方图中添加阴影线?并复现指定示例图

嘿,这个问题我刚好碰到过!要在ggplot2里给直方图或面积图添加阴影线,其实有两个实用的方法,下面我会一步步教你复现你提到的base R直方图效果,顺便也覆盖面积图的实现方式~

方法一:用ggpattern包(最简便高效)

这个包专门用来给ggplot2的图层添加各种填充图案,包括阴影线,用法非常直观。

首先得先安装并加载包:

install.packages("ggpattern")
library(ggpattern)
library(ggplot2)

接下来是复现base R中hist(mtcars$hp, density = 10)的直方图效果:

ggplot(mtcars, aes(x = hp)) +
  geom_histogram_pattern(
    bins = 12,  # 和base R默认的bins数量匹配
    pattern = "stripe",  # 指定阴影线类型
    pattern_density = 10,  # 对应base R的density参数,控制线条密度
    pattern_angle = 45,  # 阴影线角度,base R默认是45度
    fill = "white",  # 填充底色,和base R一致
    color = "black"  # 边框颜色
  ) +
  labs(x = "hp", y = "Frequency") +
  theme_bw()

这里可以调整pattern_density数值来改变线条的疏密,pattern_angle可以改成0、90等其他角度,pattern_color还能单独设置阴影线的颜色。

如果是给面积图加阴影线,用法类似,把geom_histogram_pattern换成geom_area_pattern就行,比如:

# 先构造一个面积图的示例数据
df <- data.frame(
  x = 1:10,
  y = c(2,4,5,7,6,8,9,10,8,6)
)

ggplot(df, aes(x = x, y = y)) +
  geom_area_pattern(
    pattern = "stripe",
    pattern_density = 8,
    fill = "lightblue",
    color = "black"
  ) +
  theme_bw()
方法二:手动绘制阴影线(无需额外包)

如果你不想安装新包,也可以手动计算直方图的区间,然后在每个条形里绘制斜线。步骤稍微繁琐一点,但胜在不需要依赖外部包:

library(ggplot2)

# 先获取直方图的统计数据,不绘图
hist_data <- hist(mtcars$hp, plot = FALSE)
# 把统计数据转换成数据框
hist_df <- data.frame(
  x_left = hist_data$breaks[-length(hist_data$breaks)],
  x_right = hist_data$breaks[-1],
  y_top = hist_data$counts
)

# 绘制直方图+手动添加阴影线
ggplot(hist_df) +
  # 先画条形的底色
  geom_rect(aes(xmin = x_left, xmax = x_right, ymin = 0, ymax = y_top),
            fill = "white", color = "black") +
  # 给每个条形添加斜线
  geom_segment(
    data = function(df) {
      # 生成每个条形里的斜线起点和终点
      expand.grid(
        x = seq(df$x_left, df$x_right, length.out = 10),
        y = seq(0, df$y_top, length.out = 10)
      ) |> 
        cbind(
          xend = seq(df$x_left + (df$x_right - df$x_left)/10, df$x_right, length.out = 10),
          yend = seq(0 + (df$y_top)/10, df$y_top, length.out = 10)
        )
    },
    aes(x = x, y = y, xend = xend, yend = yend),
    color = "black"
  ) +
  labs(x = "hp", y = "Frequency") +
  theme_bw()

这个方法的核心是先计算每个条形的边界,然后在每个条形内生成一系列斜线的坐标,用geom_segment绘制出来。你可以调整seq里的length.out参数来控制阴影线的密度。

内容的提问来源于stack exchange,提问作者lcgodoy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:02:42