如何使用ggplot2将变量重要性柱状图与参数估计图合并为单图
组合图实现方案
核心思路
- 先统一变量排序:按
importance降序将Variables转换为固定顺序的因子,从根源上保证左右两个面板的分类变量位置完全对齐 - 分别绘制左面板(变量重要性柱状图)、右面板(参数估计图),所有分类轴共用预处理后的因子水平
- 使用patchwork包完成水平拼接,自动适配翻转坐标的对齐逻辑,避免手动调整位置的错位问题
第一步:环境准备与数据预处理
首次使用需安装依赖包,完成变量排序预处理:
# install.packages("patchwork") library(ggplot2) library(patchwork) # 按重要性降序排列,生成固定顺序的分类因子 df <- df[order(-as.numeric(df$importance)), ] df$Variables <- factor(df$Variables, levels = df$Variables)
注:原始数据中
importance为sw自定义类,绘图前需转为数值型,否则会触发类型报错。
第二步:分别绘制两个独立面板
左面板:变量重要性柱状图
为避免和右面板重复展示变量标签,隐藏左图的y轴刻度、标签,压缩面板宽度:
p_left <- df %>% ggplot(aes(x = Variables, y = as.numeric(importance))) + geom_col(fill = "grey70", width = 0.6) + coord_flip() + scale_y_continuous(limits = c(0, 1.1), expand = c(0, 0)) + labs(y = "Importance", x = "") + theme_bw() + theme( axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid = element_blank() )
右面板:参数估计图
在原有代码基础上优化:替换手动指定的分类顺序,直接使用预处理后的固定因子水平,避免后续新增变量时手动调整的麻烦:
p_right <- df %>% ggplot(aes(x = Variables, y = Estimate, color = as.numeric(importance))) + geom_hline(yintercept = 0, color = 'red', linetype = 'dashed', lwd = 0.5) + geom_errorbar(aes(ymin = Estimate - lowerCI, ymax = Estimate + upperCI), width = 0, lwd = 1.5) + coord_flip() + geom_point(size = 4) + scale_color_gradient(low="blue", high="red") + labs(x = "") + theme_bw()
第三步:拼接为最终组合图
调整左右面板的宽度比例(可根据展示需求修改,常规左窄右宽为1:3),统一图例位置:
final_plot <- p_left + p_right + plot_layout(nrow = 1, widths = c(1, 3)) & theme(legend.position = "right")
效果说明
- 两个面板因共用同一套分类因子顺序,拼接后变量位置完全对齐,不会出现错位
- 左图柱状高度、右图点的颜色均映射为同一
importance值,实现双维度对应展示 - 左图隐藏重复的变量标签,视觉上更紧凑,信息无冗余
内容的提问来源于stack exchange,提问作者PeterPanPan
相关产品推荐
相关产品推荐

