在ggplot中使用geom_text_repel注解线

anauzrmj  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(125)

我尝试使用geom_text_repel注解ggplot中的行。但是,某些行的注解不显示。如何解决这个问题?
下面是一个可重复的例子:

library(ggplot2)
library(ggrepel)
df.1 <-
  data.frame(
    id = rep(c(1, 2, 3),each = 4),
    time = c(1, 2, 3, 4),
    x = c(1, 2, 3, 4),
    y = c(10, 23, 25, 28),
    z = c(2, 4, NA, NA)
  )

df.long <- df.1 %>% pivot_longer(cols = c(x, y, z), names_to = "class", values_to = "score")

ggplot(df.long, aes(x = time, y = score, col = class, group = class)) +
  geom_line() +
  geom_point() +
  geom_text_repel(
    data = subset(df.long, time == max(time)),
    aes(label = class),
    size = 2,
    point.padding = 0.2, 
    nudge_x = .3,
    segment.curvature = -1e-20,
    arrow = arrow(length = unit(0.015, "npc"))
  )

字符串
x1c 0d1x z的注解没有显示。另外,我如何将注解减少到每行一个?现在它有三个。非常感谢!

cigdeys3

cigdeys31#

你必须过滤最大值time的数据,每个class有一个非缺失值。此外,由于每个timeclass有多个值(每个id一个),你会得到多个标签。因此,如果你只有一个标签,使用例如dplyr::distinct来消除重复:

library(dplyr, warn=FALSE)
library(ggplot2)
library(ggrepel)

df_labels <- df.long |>
  drop_na() |> 
  filter(time == max(time), .by = class) |> 
  distinct(time, class, score)

ggplot(df.long, aes(x = time, y = score, col = class, group = class)) +
  geom_line() +
  geom_point() +
  geom_text_repel(
    data = df_labels,
    aes(label = class),
    size = 2,
    point.padding = 0.2,
    nudge_x = .3,
    arrow = arrow(length = unit(0.015, "npc"))
  )
#> Warning: Removed 6 rows containing missing values (`geom_line()`).
#> Warning: Removed 6 rows containing missing values (`geom_point()`).

字符串


的数据

相关问题