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

如何在ggplot的facet_wrap分面图末尾添加全数据汇总图?

在ggplot分面图末尾添加汇总数据分布图的解决方案

方法1:用grid.arrange拼接独立图表

可以通过gridExtra包的grid.arrange实现,步骤如下:

  1. 安装并加载依赖包:
install.packages("gridExtra")
library(gridExtra)
  1. 分别绘制分面图和汇总图:
# 分面图
p_facet <- ggplot(test, aes(x=normalizedtime, fill=cut(normalizedtime, bins))) +
  geom_histogram(show.legend = FALSE, binwidth = 0.06) +
  scale_fill_manual(values=cut.cols) +
  scale_x_continuous(breaks=c(-1,0,1), labels=c('dusk', 'dawn','dusk'), limits = c(-1.1,1.1)) +
  theme_minimal() +
  facet_wrap(~station)

# 汇总图
p_all <- ggplot(test, aes(x=normalizedtime, fill=cut(normalizedtime, bins))) +
  geom_histogram(show.legend = FALSE, binwidth = 0.06) +
  scale_fill_manual(values=cut.cols) +
  scale_x_continuous(breaks=c(-1,0,1), labels=c('dusk', 'dawn','dusk'), limits = c(-1.1,1.1)) +
  theme_minimal() +
  ggtitle('All Data')
  1. 按网格布局拼接,适配8个分面+1个汇总的3x3网格:
grid.arrange(p_facet, p_all, 
             layout_matrix = matrix(c(1,1,1,
                                      1,1,1,
                                      1,1,2), nrow=3, byrow=TRUE))

方法2:在ggplot内整合数据(推荐,排版更统一)

你之前的代码存在两个核心问题:cuts <- cut只是赋值了函数,未实际对数据做分箱;汇总图的分箱逻辑未与分面图对齐。修正后的代码如下:

bins <- 200
cols <- c("#0072B2",'#253f4b',"#0072B2","#D55E00","#F0E442","#D55E00")
colGradient <- colorRampPalette(cols)
cut.cols <- colGradient(bins)

# 提前对全数据做分箱,确保分面与汇总图的颜色映射一致
test$time_cut <- cut(test$normalizedtime, bins)

# 生成包含汇总数据的数据集:复制原数据并将station改为"All Data",合并到原数据
test_combined <- rbind(test, transform(test, station = "All Data"))

# 绘制整合后的分面图
ggplot(test_combined, aes(x=normalizedtime, fill=time_cut)) +
  geom_histogram(show.legend = FALSE, binwidth = 0.06) +
  scale_fill_manual(values=cut.cols) +
  scale_x_continuous(breaks=c(-1,0,1), labels=c('dusk', 'dawn','dusk'), limits = c(-1.1,1.1)) +
  theme_minimal() +
  facet_wrap(~station)

关键修正说明:

  • 提前基于全数据集做分箱,避免分面图与汇总图的颜色分箱出现差异
  • 通过rbind将汇总数据(修改station为"All Data")合并到原数据,让facet_wrap自动生成汇总面板
  • 移除冗余的scale_color_manual(仅使用fill映射,无需color映射)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:57:52