geom_text 值相同时标签交换位置

geom_text labels swap places when values are the same

我正在尝试使用 geom_text 作为折线图的图例,但我还需要将 COUNT 作为标签(工作要求)。

当我 运行 下面的代码时,我可以获得标签、值和类别名称,并以不同的方式设置它们的格式,以便图例更加明显。

但如果最终的 COUNT 个相同,则每次代码 运行 时标签的顺序都会改变。因此,有时正确的 COUNT 与图例的正确标签对齐,但 运行 又一次,标签会混淆。

df <- data.frame(YEAR = c(2017,2018,2019,2017,2018,2019,2017,2018,2019),
            SPLIT = c("Cat A","Cat A","Cat A","Cat B","Cat B","Cat B","Cat C","Cat C","Cat C"),
            COUNT = c(11,12,15,6,8,12,15,14,12)
                 )
ggplot(df, aes(YEAR, COUNT, label = COUNT, colour = SPLIT, group = SPLIT)) +
geom_line(size = 1) +
scale_x_continuous(labels = as.character(df$YEAR), breaks =df$YEAR, limits = c(min(df$YEAR), max(df$YEAR+0.3)))+
geom_text_repel(data = subset(df, YEAR == max(YEAR)), aes(label = SPLIT), show.legend = FALSE, size = 4, fontface = "bold", hjust = "left",nudge_x = 0.2,direction = "y", segment.color = NA) +
  geom_text_repel(data = subset(df, YEAR == max(YEAR)), aes(label = COUNT), show.legend = FALSE, size = 3,direction = "y", segment.color = NA) +
  theme(legend.position="none")

我知道我可以使用 paste(Col1,Col2) 创建一个额外的字段并且只使用一个 geom_text,但是标签的格式相同,我希望它们不同。

我试过直接标签,但标签靠得太近了。我缩小了字体大小,但还是靠得太近了。

我想这里有几个问题:

  1. 我可以调整我的代码来修复标签的顺序吗? 或
  2. 我可以为同一字段的两个部分设置不同的格式吗? 或者.
  3. 如何使用 directlabels 增加标签的间距?

感谢您的帮助。

如何删除 geom_text_repels 之一并传入 SPLIT2 变量,它利用 glue 包连接 SPLITCOUNT

这样做会更改 Cat CCat B 的标签顺序。

我还建议您考虑将 nudge_x0.2 更改为 0.05

library(tidyverse)
library(lubridate)
library(ggrepel)
library(glue)

df <- data.frame(YEAR = c(2017,2018,2019,2017,2018,2019,2017,2018,2019),
            SPLIT = c("Cat A","Cat A","Cat A","Cat B","Cat B","Cat B","Cat C","Cat C","Cat C"),
            COUNT = c(11,12,15,6,8,12,15,14,12)
                 )


df <- df %>% 
  mutate(
    SPLIT2 = glue("{SPLIT} - {COUNT}")
  )

ggplot(df, aes(YEAR, COUNT, label = COUNT, colour = SPLIT, group = SPLIT)) +
geom_line(size = 1) +
scale_x_continuous(labels = as.character(df$YEAR), 
                   breaks =df$YEAR, 
                   limits = c(min(df$YEAR), 
                              max(df$YEAR+0.3)))+
  geom_text_repel(data = subset(df, YEAR == max(YEAR)),
                  aes(label = SPLIT2),
                  show.legend = FALSE,
                  size = 4,
                  fontface = "bold",
                  hjust = "left",
                  nudge_x = 0.2,
                  direction = "y",
                  segment.color = NA) +
  theme(legend.position="none")