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

如何将base R堆叠条形图迁移至ggplot2并以黑白纹理区分层级

实现步骤

1. 安装加载依赖包

需要用到ggplot2做绘图基础,ggpattern实现纹理填充功能,未安装可以先执行安装:

install.packages(c("ggplot2", "ggpattern"))

加载包:

library(ggplot2)
library(ggpattern)

2. 数据格式转换

ggplot2要求输入长格式数据,先将原有table类数据转换为标准数据框:

df_well <- as.data.frame(p_well)
colnames(df_well) <- c("function_type", "position", "percentage")

3. 绘制带黑白纹理的堆叠条形图

ggplot(df_well, aes(x = position, y = percentage, pattern = function_type)) +
  geom_col_pattern(
    fill = "white",
    colour = "black",
    pattern_fill = "black",
    pattern_colour = "black"
  ) +
  # 自定义8种不同纹理对应8类功能
  scale_pattern_manual(
    values = c(
      "adjective" = "stripe",
      "as_well" = "crosshatch",
      "dispreferred_marker" = "stripe",
      "manner_adverb" = "circle",
      "quote_marker" = "wave",
      "restart_marker" = "dots",
      "turn_preface" = "grid",
      "unclear" = "none"
    ),
    name = "Function type"
  ) +
  labs(
    title = "Functions of 'well' by positions in turn",
    x = "Positions",
    y = "%"
  ) +
  theme_bw() +
  theme(
    plot.title = element_text(size = 10, hjust = 0.5),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 8),
    legend.text = element_text(size = 8),
    legend.position = "top"
  )

如果纹理区分度不足,可在geom_col_pattern中新增pattern_density、pattern_angle参数,给不同分类设置差异化的纹理密度、角度即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:15:04