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

ggplot2中geom_col排序与facet_grid分面标签修改问题

完整可运行代码
library(ggplot2)

# 数据预处理
test_label_map <- c(
  "0" = "Test Under",
  "1" = "Test Medium",
  "2" = "Test Above Avg",
  "3" = "Test Excellent"
)
df$test_level <- factor(df$test_level, levels = names(test_label_map), labels = test_label_map)

target_var_order <- c(
  "White", "Black", "Hispanic", "Other Race",
  "Male", "Female",
  "Less than HS", "Some HS", "Graduate HS",
  "Some College or\nTechnical School", "Graduate College\nor Higher"
)
df$var <- factor(df$var, levels = target_var_order, ordered = TRUE)

# 可视化
ggplot(df, aes(x = percent, y = var, fill = group_factor_ordered)) +
  geom_col(orientation = "y", color = "black") +
  facet_grid(group_factor_ordered ~ test_level,
             scales = "free", space = "free_y") +
  labs(title = "Demographic breakdown of Testing Level",
       y = "",
       x = "Percent") +
  theme_minimal() +
  theme(legend.position = "none",
        strip.text.y = element_blank())

关键注意事项

  • 因子排序必须严格匹配原数据中的字符串,比如原数据中带换行的"Some College or\nTechnical School"不能省略换行符,否则排序不生效。
  • 直接修改因子水平标签比仅依赖labeller更稳定,因为ggplot会优先使用因子自身的标签进行渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:10:16