结合标签与`geom_text_repel`吗?

时间:2019-10-21 18:12:15

标签: r ggplot2 ggrepel

我如何创建占两点的标签?在此示例中,我感兴趣的是制作一个标签,该标签是“ 6”和“ 8”条的总和,并且有一条线指向它们。目前我有:

library(tidyverse)
library(ggrepel)

mtcars %>% 
  group_by(cyl) %>% 
  summarise(mpg = median(mpg)) %>% 
  ggplot(aes(factor(cyl), mpg, label = mpg)) +
  geom_bar(stat = "identity") +
  geom_text_repel()

separate_labels

该标签将与下面的代码大致等效,并且会位于6条和8条之间的上方和中间,并带有指向每个条的线。

label <- mtcars %>% 
  group_by(cyl) %>% 
  summarise(mpg = median(mpg)) %>% 
  filter(cyl >= 6) %>% 
  summarise (mpg = sum(mpg))

1 个答案:

答案 0 :(得分:1)

根据@JonSpring的评论,我写的广义答案是:

df <- 
mtcars %>% 
  group_by(cyl) %>% 
  summarise(mpg = median(mpg)) 

eight <- df %>% filter(cyl == 8) %>% pull(mpg)
six <- df %>% filter(cyl == 6) %>% pull(mpg)
upper <- max(c(six, eight))
total <- sum(six, eight)

df %>% 
  ggplot(aes(factor(cyl), mpg)) +
    geom_bar(stat = "identity") +
    annotate("segment", x = 2, xend = 2.5, y = six, yend = upper + 10) +
    annotate("segment", x = 3, xend = 2.5, y = eight, yend = upper + 10) +
    annotate("label", x = 2.5, y = upper + 10, label = total)

enter image description here