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

ggplot2分面柱状图:按组排序条形并省略未使用的因子水平

问题描述

我制作的柱状图效果不符合预期:
![当前柱状图效果 wide具体实例arts自体现�一定的处理:

structure(list(author = c("Me", "Me", "Them", "Them", "Them", 
"Them", "Them", "You", "You"), display_name = c("Raceway", "Pulverized coal-fired boiler", 
"Hollow fiber membrane", "Permeation", "Residence time distribution", 
"Fluidization", "Rotary kiln", "Rotary kiln", "Raceway"), n = c(4, 
2, 4, 4, 3, 2, 2, 3, 3), sum_score = c(3.69998413, 1.4438111, 
2.5820569, 2.32903219, 1.90571574, 1.86841225, 1.42931327, 2.8, 
2.2)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"
))

我原本按组对关键词列因子化的代码:

df <- transform(df, category2 = factor(paste(author, display_name)))
df <- transform(df, category2 = reorder(category2, rank(sum_score)))

ggplot绘图代码:

ggplot(df, aes(x = category2, y = sum_score, fill = author)) +
  geom_bar(stat = "identity") +
  facet_wrap(. ~ author, scales = "free_x", nrow = 3) +
  scale_x_discrete(labels = df$display_name, breaks = df$category2) +
  scale_y_continuous(limits = c(0, max(DF3$sum_score))) +
  scale_fill_manual("legend", values = c("You" = "#006699", "Me" = "orange", "Them" = "#720016")) +
  ylab("") +
  xlab("") +
  theme_minimal() + 
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  ) +
  coord_flip()
解决方案

问题出在你创建了跨组合并的category2因子,导致每个分面的轴标签被强制关联所有组的组合值,无法自动隐藏无数据的标签。调整方案如下:

1. 按组内排序生成有序因子

无需合并author和display_name,直接在每个author组内,根据sum_score对display_name排序生成有序因子:

```r
ggplot(df, aes(x = display_name, y = sum_score, fill = author)) +
  geom_col() +  # 等价于geom_bar(stat="identity"),写法更简洁
  facet_wrap(. ~ author, scales = "free_y", nrow = 3) +
  scale_y_continuous(limits = c(0, max(df$sum_score))) +  # 修正变量名,统一用df
  scale_fill_manual(values = c("You" = "#006699", "Me" = "orange", "Them" = "#720016")) +
  labs(x = "", y = "") +
  theme_minimal() + 
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  ) +
  coord_flip()

效果说明

  • 每个author组内的display_name会单独按sum_score排序,不会和其他组的标签混淆;
  • scales="free_y"配合coord_flip(),自动隐藏当前分面无数据的标签,只显示有对应数据的项;
  • geom_col()是geom_bar(stat="identity")的简化写法,功能完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 07:04:51