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

如何在R语言中绘制各组X轴值唯一的分组柱状图?

我明白你想要的效果——给销量前十的发行商各自单独展示他们最畅销的前五款游戏,而不是之前用分面时那种不符合预期的呈现。咱们先从修正数据处理的核心问题开始,再调整绘图逻辑:

第一步:修正数据处理逻辑

你之前的df2构建存在问题:summarise是用来做聚合统计的,不能直接保留Name、Sales这类非聚合列,这会导致数据混乱。我们改用slice_max来精准筛选每个发行商的前五款畅销游戏:

library(dplyr)
library(ggplot2)

# 1. 先算出每个发行商的总销量,筛选出前十的发行商
top_publishers <- df %>%
  group_by(Publisher) %>%
  summarise(total_pub_sales = sum(Sales, na.rm = TRUE)) %>%
  top_n(10, total_pub_sales) %>%
  arrange(desc(total_pub_sales)) %>%
  pull(Publisher) # 提取成向量,方便后续筛选目标发行商

# 2. 筛选目标发行商的游戏,再取每个发行商销量前五的游戏
top_games_per_pub <- df %>%
  filter(Publisher %in% top_publishers) %>%
  group_by(Publisher) %>%
  slice_max(Sales, n = 5, with_ties = FALSE) %>% # with_ties=FALSE避免并列销量时超出5个
  ungroup() %>%
  # 可选:固定每个发行商下游戏的排序(按销量降序)
  arrange(Publisher, desc(Sales)) %>%
  mutate(Name = factor(Name, levels = unique(Name)))
第二步:绘制符合需求的分面柱状图

现在用ggplot生成每个发行商独立分面的柱状图,调整参数让布局更清晰:

ggplot(top_games_per_pub, aes(x = Name, y = Sales)) +
  geom_col(fill = "#2E86AB") + # 自定义填充色,也可以按发行商区分颜色
  facet_wrap(~Publisher, scales = "free_y", ncol = 2) + # scales="free_y"让每个分面y轴自适应,ncol控制列数
  coord_flip() +
  labs(
    x = "Game Title",
    y = "Total Sales (millions of copies)",
    title = "Top 5 Best-Selling Games for Top 10 Publishers"
  ) +
  theme_minimal() +
  theme(
    strip.text = element_text(face = "bold", size = 10),
    axis.text.y = element_text(size = 8)
  )
可选:同一图表内的分组呈现

如果你不想用分面,想把所有发行商放在同一个图里对比,可以用以下代码:

ggplot(top_games_per_pub, aes(x = Publisher, y = Sales, fill = Name)) +
  geom_col(position = position_dodge(width = 0.8)) +
  coord_flip() +
  labs(
    x = "Publisher",
    y = "Total Sales (millions of copies)",
    title = "Top 5 Best-Selling Games for Top 10 Publishers"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

简单总结下之前的问题:你误用了summarise来保留原始行数据,这不符合它的聚合用途,而slice_max是筛选组内Top N行的标准方法,能保证数据准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:07:53