【问题标题】:How do I correctly select the label to place on top of the highest point of the Y-axis of a facet-separated plot?如何正确选择标签以放置在分面分隔图 Y 轴最高点的顶部?
【发布时间】:2021-12-29 21:16:29
【问题描述】:

我有一个情节,我用每个组的方面分开。在 Y 轴的最高点我想放置相应的 Y 值,为此我使用 ggtext 包和 geom_richtext() 函数。虽然我在geom_richtext() 函数中使用了group = Group,但标签并没有像我预期的那样出现。

在 MWE 中,我希望 A、B 和 C 组的面分别具有 100、500 和 1000 的值,分别出现在每个峰的顶部。有人可以帮我提个建议吗?

library(ggplot2)
library(ggtext)

Group <- c("A", "B", "C")
Time <- 0:10

DF <- expand.grid(Time = Time,
                  Group = Group)

DF$Y <- c(rep(1,5), 100, rep(1,5),
          rep(1,5), 500, rep(1,5),
          rep(1,5), 1000, rep(1,5))

ggplot(data = DF,
       aes(x = Time,
           y = Y)) +
  geom_line() +
  facet_grid(Group ~ .) +
  geom_richtext(aes(label = max(Y),
                    group = Group)) +
  theme_bw()

【问题讨论】:

    标签: r ggplot2 text label ggtext


    【解决方案1】:

    一种选择是将过滤后的数据集传递给geom_richtext,其中仅包括每个Group 的最大值:

    library(ggplot2)
    library(ggtext)
    library(dplyr)
    
    ggplot(data = DF,
           aes(x = Time,
               y = Y)) +
      geom_line() +
      facet_grid(Group ~ .) +
      geom_richtext(data = DF %>% group_by(Group) %>% slice_max(Y, n = 1), aes(label = Y,
                        group = Group)) +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 2014-07-07
      • 2017-10-24
      • 1970-01-01
      相关资源
      最近更新 更多