如何将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
相关产品推荐
相关产品推荐

