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

R语言按Tier、Region对比2015与2016年销售额的绘图问题

你提供的代码存在两个核心问题:

  • 汇总后的数据是宽格式,没有ggplot映射所需的Sales、Year字段
  • 没有配置按Region维度拆分的分面规则

完整可运行代码

首先需要加载tidyverse依赖包:

library(tidyverse)

数据处理+绘图代码:

# 加载你提供的数据集
dataframe <- structure(list(AccountId = c(1116L, 1116L, 2391L, 2391L, 2397L, 
    2400L, 2400L, 2404L, 2406L, 2408L), AccountName = c("Account1", 
    "Account1", "Account2", "Account2", "Account3", "Account4", "Account4", 
    "Account5", "Account6", "Account7"), Region = c("West", "West", 
    "East", "East", "East", "East", "East", "East", "East", "East"
    ), Division = c("DIAMONDBACK", "DIAMONDBACK", "MINUTEMEN", "MINUTEMEN", 
    "MINUTEMEN", "MINUTEMEN", "MINUTEMEN", "EMPIRE", "BIG APPLE", 
    "BIG APPLE"), City = c("PHOENIX W", "PHOENIX W", "HARTFORD", 
    "HARTFORD", "WORCESTER", "PORTLAND", "PORTLAND", "BRIDGEPORT", 
    "JERSEY CITY", "JERSEY CITY"), State = c("AZ", "AZ", "CT", "CT", 
    "MA", "ME", "ME", "CT", "NJ", "NJ"), Tier = c("Low", "Low", "Med", 
    "Med", "Med", "High", "High", "Low", "Med", "High"), Month = c("Aug", 
    "Oct", "Jun", "Mar", "Sep", "Jul", "Feb", "Mar", "Mar", "Aug"
    ), Sales2015 = c(0, 10500.78, 0, 19881, 3684.48, 0, 2631.31, 
    4153.89, 0, 0), Sales2016 = c(13208.52, 23114.91, 6627, 13254, 
    0, 10525.24, 42812.62, 3918.77, 6951.86, 10994.54), Units2015 = c(0, 
    3, 0, 9, 1, 0, 1, 1, 0, 0), Units2016 = c(4, 7, 3, 6, 0, 4, 17, 
    1, 2, 4), TargetAchevied2015 = c(0.7, 0.84, 1.15, 1.33, 1.02, 
    1.03, 1.08, 0.79, 1.12, 1.11), TargetAchevied2016 = c(1.53, 1.31, 
    1.29, 1.17, 1.53, 1.45, 0.99, 1.46, 1.02, 1.54)), row.names = c(NA, 
    10L), class = "data.frame")

# 核心处理逻辑
dataframe %>%
  group_by(Region, Tier) %>%
  summarise(TotalSales2015 = sum(Sales2015), 
            TotalSales2016 = sum(Sales2016),
            .groups = "drop") %>%
  # 宽表转长表,生成Year和Sales字段供ggplot映射
  pivot_longer(cols = starts_with("TotalSales"),
               names_to = "Year",
               names_prefix = "TotalSales",
               values_to = "Sales") %>%
  ggplot(aes(x = Tier, y = Sales, fill = Year)) +
  geom_col(position = position_dodge(0.9), alpha = 0.8) +
  # 调整数值标签位置,避免和柱子重叠
  geom_text(aes(label = round(Sales, 1)), 
            position = position_dodge(0.9), 
            vjust = -0.3, size = 3.5) +
  # 按Region分面实现两个区域的对比
  facet_wrap(~Region) +
  labs(y = "销售额") +
  theme_minimal()

调整说明

  1. 汇总后新增.groups = "drop"取消分组,避免后续处理产生告警
  2. 用pivot_longer把两年的销售额列转换为长格式,满足ggplot的映射要求
  3. 用facet_wrap(~Region)实现按Region维度拆分对比,匹配需求
  4. 统一调整了柱状图和数值标签的对齐参数,保证标签显示在对应柱子的正上方

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:30:05