2

我将如何创建一个占两点的标签?在这个例子中,我感兴趣的是制作一个标签,它是“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()

分离标签

标签将大致等同于下面的代码,并且将位于 6 和 8 条之间的某个位置,线条指向每个条。

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

1 回答 1

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)

在此处输入图像描述

于 2019-10-22T02:53:06.460 回答