首页 > 解决方案 > 如何在 ggplot 折线图中注释累积向量的最终值?

问题描述

我有一个 ggplot 折线图,它显示了游戏中两个累积得分向量(每个团队一个)。现在我对它目前的样子很满意,但我想在行尾注释一个团队的当前得分(所以是累积值)。

球队的得分过程如下所示:

> testVectorJG
 [1]  17 138  45   0 182 117  49   0  94   0  57   0
> testVectorJW
 [1] 145  64 157 182   0  65 133 182 136 202 105 202

我的数据框如下所示:

test_df <- tribble(~puntenvector, ~Team, ~Rondenummer, ~cumPunten,
                   145, 'Jaap, &, Wil', 1, 145,
                   64, 'Jaap, &, Wil', 2, 209,
                   157, 'Jaap, &, Wil', 3, 366,
                   182, 'Jaap, &, Wil', 4, 548,
                   0, 'Jaap, &, Wil', 5, 548,
                   65, 'Jaap, &, Wil', 6, 613,
                   133, 'Jaap, &, Wil', 7, 746,
                   182, 'Jaap, &, Wil', 8, 928,
                   136, 'Jaap, &, Wil', 9, 1064,
                   202, 'Jaap, &, Wil', 10, 1266,
                   105, 'Jaap, &, Wil', 11, 1371,
                   202, 'Jaap, &, Wil', 12, 1573,
                   17, 'Jasper, &, Gijs', 1, 17,
                   138, 'Jasper, &, Gijs', 2, 155,
                   45, 'Jasper, &, Gijs', 3, 200,
                   0, 'Jasper, &, Gijs', 4, 200,
                   182, 'Jasper, &, Gijs', 5, 382,
                   117, 'Jasper, &, Gijs', 6, 499,
                   49, 'Jasper, &, Gijs', 7, 548,
                   0, 'Jasper, &, Gijs', 8, 548,
                   94, 'Jasper, &, Gijs', 9, 642,
                   0, 'Jasper, &, Gijs', 10, 642,
                   57, 'Jasper, &, Gijs', 11, 699,
                   0, 'Jasper, &, Gijs', 12, 699)

我正在创建我当前的 ggplot 如下:

ggplot(test_df, aes(x = Rondenummer, y = cumPunten, colour = Team, group = Team)) +
    geom_line() +
    labs(y = "Punten",
         title = "Cumulatief aantal punten (inclusief roem) per ronde") +
    theme_grey()

那么,如何以一种不错的、不重叠的方式显示每支球队的当前得分呢?

提前谢谢!

标签: rggplot2

解决方案


您可以包含一个 geom_text 图层,该图层仅绘制数据的一个子集(对应于迄今为止播放的最大轮次)。您可以通过将子集函数传递给该层的data参数来实现这一点。

此外,对于不重叠的东西,你可以玩一点nudge_xand nudge_y。在这个例子中,我只添加了一个 nudge_y。另一种选择是使用geom_text_repel, 从ggrepel包中,它为您处理不重叠的事情。

max_round <- max(test_df$Rondenummer)
ggplot(test_df, aes(x = Rondenummer, y = cumPunten, colour = Team, group = Team)) +
  geom_line() +
  geom_text(data = function(x) subset(x, Rondenummer == max_round),
            aes(label = cumPunten),
            nudge_x = 0.75) +
  labs(y = "Punten",
       title = "Cumulatief aantal punten (inclusief roem) per ronde") +
  theme_grey()

结果图

ggrepel 解决方案:

max_round <- max(test_df$Rondenummer)
ggplot(test_df, aes(x = Rondenummer, y = cumPunten, colour = Team, group = Team)) +
  geom_line() +
  ggrepel::geom_text_repel(data = function(x) subset(x, Rondenummer == max_round),
            aes(label = cumPunten)) +
  labs(y = "Punten",
       title = "Cumulatief aantal punten (inclusief roem) per ronde") +
  theme_grey()

格格佩尔


推荐阅读