我正在尝试使用
ggplot
来注释 geom_text_repel
中的行。但是,某些行的注释没有显示。如何解决这个问题?
这是一个可重现的示例:
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"))
)
z
的注释未显示。另外,如何将注释减少到每行一个?现在它有三个。非常感谢!
您必须过滤数据以获得最大
time
,并且每个 class
具有非缺失值。此外,由于每个 id
和 time
有多个值(每个 class
一个),因此您会获得多个标签。因此,如果您只有一个标签,请使用例如删除重复项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()`).