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

如何用ggplot2批量生成带数据表格的门店销售图表?

批量生成门店销售图+表组合页面的解决方案

问题背景

需要为多个门店批量生成可视化页面,每个页面包含:

  • 单店两款产品的年度销售折线图
  • 下方附带该店全周期总销售额及次年预测销售额的表格

已实现单店图+表生成和批量单独图表,但批量添加表格时触发only 'grobs' allowed in "gList"错误。

错误原因

  1. 原store_table函数逻辑错误:
    • 过滤数据后未返回有效对象,且错误使用整个projected数据框生成表格,未针对单个门店过滤
    • 直接调用grid.table不会返回可用于组合的grob对象,需用tableGrob生成标准grob
  2. grid.arrange无法直接接收两个列表参数,需为每个门店单独组合图和表后再批量处理

修改后的完整代码

1. 加载依赖包与数据

library(ggplot2)
library(grid)
library(gridExtra)
library(dplyr)
library(purrr)

# 可复现数据
sales <- data.frame(Year=c(2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019), 
                        Store_Number=c(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3), 
                        Sales=c(200, 250, 50, 150, 200, 75, 100, 450, 150, 150, 200, 175), 
                        Product=c("Pizza", "Salad", "Pizza", "Salad", "Pizza", "Salad", "Pizza", "Salad", "Pizza", "Salad", "Pizza", "Salad"))
projected <- data.frame(Store_Number=c(1,2,3), 
                        TotalSales=c(1000,500,650),
                        FutureSales=c(1000,600,400))  

2. 定义单店图生成函数

store_plot <- function(store_of_interest) {
  sales %>%
    filter(Store_Number == store_of_interest) %>%
    ggplot(aes(x = Year, y = Sales, linetype = Product, 
             color = Product, shape = Product)) +
    geom_point(size=1.5) + geom_line(size=.75) + theme_classic() +
    theme(legend.title = element_blank()) +
    labs(x = "Year", y = "Sales") +
    ggtitle(paste("Store Number", store_of_interest)) + 
    theme(plot.title = element_text(hjust = 0.5)) +
    scale_color_manual(values = c("#00AFBB", "#FC4E07"))
}

3. 定义单店表格grob生成函数

# 定义表格统一样式
mytheme <- gridExtra::ttheme_default(
  core = list(padding = unit(c(2.5, 2.5), "mm")))

store_table_grob <- function(store_of_interest) {
  # 过滤单个门店数据并移除门店编号列
  tbl_data <- projected %>% 
    filter(Store_Number == store_of_interest) %>% 
    select(-Store_Number)
  
  # 返回可用于grid组合的tableGrob对象
  tableGrob(tbl_data, theme = mytheme, rows = NULL)
}

4. 组合单店图与表,并批量生成/保存

# 获取所有门店编号
store_ids <- unique(sales$Store_Number)

# 为每个门店生成图+表的组合页面
map(store_ids, function(id) {
  p <- store_plot(id)
  tbl <- store_table_grob(id)
  
  # 组合图和表
  combined <- grid.arrange(p, tbl, nrow = 2, heights = c(4,1))
  
  # 可选:自动保存每个门店的报告为图片文件
  ggsave(paste0("Store_", id, "_report.png"), combined, width = 8, height = 6)
  
  return(combined)
})

关键修改点说明

  • 修正表格生成逻辑:返回tableGrob生成的标准grob对象,确保只使用当前门店的过滤数据
  • 遍历每个门店编号,单独组合对应门店的图和表,避免直接传递列表给grid.arrange
  • 增加可选保存步骤,自动将每个门店的报告导出为独立图片文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:00:22