【问题标题】:How to make the rows within a facet appear according to the level of another vector?如何使构面内的行根据另一个向量的级别出现?
【发布时间】:2020-12-18 22:40:37
【问题描述】:

目标是让“名称”在每个方面中从上到下显示“开始时间”的增加。方面 A 是错误的;方面 B 是正确的。

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"
)

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_x_reordered() +
  scale_y_continuous(expand = c(0,0))

【问题讨论】:

  • 几乎所有关于 SO 的问题,包括 ggplot2"order of " 都使用 factors 解决,并控制 @987654326 @ 在其中。
  • 我看到了你的解决方案。谢谢。我看到了许多与您类似的示例,但没有一个以相同的方式使用 order() 函数。另外,我想我误解了“级别”参数的含义。

标签: r ggplot2 facet


【解决方案1】:
my_tribble$name <- factor(my_tribble$name, levels = my_tribble$name[order(-my_tribble$startTime)])
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))

【讨论】:

  • 您对“-my_tribble$startTime”的使用会产生很大的不同。为什么需要“-”?似乎我应该能够将最小的 startTime 保留为最低值......而不是颠倒顺序。
  • y 轴在底部具有最低(排序优先)的值。由于您希望从顶部向下跟踪最低值,因此我们需要颠倒顺序。一种方法是使用R的rev函数;另一种方式是排序值的负数。
猜你喜欢
  • 2021-10-24
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多