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

在ggplot2的facet_wrap中按y轴对x轴分面独立重排序

分面内按数值降序重排序坐标轴

你的示例代码

set.seed(1)
x <- replicate(n = 5, 'left')
y <- replicate(n = 5, 'right')
dir <- c(x,y)
quantity <- sample(seq(1,100), 10)
names <- rep(letters[1:5],2)
tb <- tibble(dir,quantity,names) %>%
  group_by(dir) %>%
  arrange(desc(quantity))

tb %>%
  ggplot(aes(x = fct_inorder(names), quantity)) +
    geom_bar(stat = 'identity', color = 'black') +
  coord_flip() +
  facet_wrap(~dir, scales = "free")

当前图表效果

当前分面图

需求

左右两个分面的x轴(经coord_flip()后对应视觉上的y轴)都按quantity的降序重排序。


解决办法

之所以没实现分面内各自排序,是因为fct_inorder()是按整个数据框的行顺序设置因子水平,不是每个分组内部的顺序。可以用以下两种方法解决:

方法1:分组内用fct_reorder()直接排序

在分组里用fct_reorder(),通过-quantity指定按降序排列:

library(tidyverse)

set.seed(1)
x <- replicate(n = 5, 'left')
y <- replicate(n = 5, 'right')
dir <- c(x,y)
quantity <- sample(seq(1,100), 10)
names <- rep(letters[1:5],2)
tb <- tibble(dir,quantity,names) %>%
  group_by(dir) %>%
  mutate(names = fct_reorder(names, -quantity))  # 按quantity降序排列names

tb %>%
  ggplot(aes(x = names, quantity)) +
    geom_bar(stat = 'identity', color = 'black') +
  coord_flip() +
  facet_wrap(~dir, scales = "free")

方法2:分组排序后手动设置因子水平

先分组按quantity降序排列,再把names转为因子,水平用分组内排序后的唯一值:

tb <- tibble(dir,quantity,names) %>%
  group_by(dir) %>%
  arrange(desc(quantity)) %>%
  mutate(names = factor(names, levels = unique(names)))  # 用分组内排序后的顺序作为因子水平

tb %>%
  ggplot(aes(x = names, quantity)) +
    geom_bar(stat = 'identity', color = 'black') +
  coord_flip() +
  facet_wrap(~dir, scales = "free")

两种方法都能让每个分面里的标签按对应quantity从大到小排列,满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:12:42