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

如何在ggplot2分面内按startTime升序排列name条目?

解决分面内按startTime排序name的问题

看起来你需要让每个分面里的name按照startTime从小到大的顺序从上到下展示,目前Facet A的顺序是反的,我来帮你修正这个问题。

问题根源

当前代码里的scale_x_reordered()没有针对每个分面单独处理排序逻辑,再加上coord_flip()反转了轴的显示顺序,导致Facet A里startTime更小的unit1跑到了最下面,而不是我们想要的最上方。

解决方案

我们需要在每个分面(area)内部,单独调整name的排序,结合coord_flip()的显示逻辑来设置因子水平。具体步骤如下:

  1. 预处理数据,按分面分组排序
    先对数据按area分组,把每个组内的name按照startTime的降序设置为因子水平——这样coord_flip()之后,startTime小的name就会出现在上方。
library(tidyverse)

my_tribble <- tribble(
  ~name, ~order.x, ~startTime, ~endTime, ~order.y, ~endTime.y, ~diff, ~area,
  "unit1", "dump", 0, 1, "wait", 2, 2, "A",
  "unit3", "dump", 5, 7, "wait", 9, 4, "A",
  "unit4", "dump", 8, 9, "wait", 10, 2, "B",
  "unit2", "dump", 17, 20, "wait", 23, 6, "B"
) %>%
  # 按area分组,将name按startTime降序设置为因子水平
  group_by(area) %>%
  mutate(name = fct_reorder(name, desc(startTime))) %>%
  ungroup()
  1. 绘制修正后的图表
    预处理完数据后,直接画图即可,不需要再用scale_x_reordered():
ggplot(my_tribble) + 
  geom_linerange(aes(ymin = startTime, ymax = endTime.y, x = name),
                 position = position_dodge(width = 0.2), size = 2) + 
  facet_grid(area ~ ., scales = "free_y") + 
  coord_flip() + 
  scale_y_continuous(expand = c(0,0))

效果说明

这样处理后:

  • Facet A里unit1(startTime=0)会显示在最上方,unit3(startTime=5)在下方
  • Facet B里unit4(startTime=8)在上方,unit2(startTime=17)在下方
    完全符合你要求的“每个分面内name按startTime从小到大从上到下显示”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:19:59