如何在geom_label_repel中向后发送覆盖其他标签的箭头?

时间:2018-10-15 20:52:04

标签: r ggplot2 ggrepel

这似乎很简单,但是我找不到任何ggrepel::geom_label_repel()来实现此目的的论据。

数据样本:

df <- structure(list(Athletename = c("Aries Merritt", "Damian Warner"
), Score = c(12.8, 13.44), Event = c("110m hurdles", "110m hurdles"
), Points = c(1135, 1048), Record = c("World Record", "Decathlon Record"
), score_and_points = c("12.8s, 1135pts", "13.44s, 1048pts")), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("Athletename", 
"Score", "Event", "Points", "Record", "score_and_points"))

ggplot2代码:

ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
  geom_point(data = df, aes(x=Score, y=Points, colour=Record)) +
  geom_label_repel(data = df, 
                   aes(x=Score, y=Points, label = Athletename), 
                   direction = "x",
                   nudge_x = -10) +
  geom_label_repel(data = df, 
                   aes(x=Score, y=Points, label = score_and_points), 
                   direction = "y",
                   nudge_y = -200) +
  scale_y_continuous(name = "Points", 
                     breaks = seq(0,1500,100),
                     limits = c(0,1500)) +
  scale_x_reverse(name = "110m hurdles time (m)",
                     breaks = seq(29,12,-1),
                     limits=c(29,12)) +
  theme(legend.title = element_blank(), legend.position = "top")

enter image description here

1 个答案:

答案 0 :(得分:8)

很麻烦,但可以使用:添加一个geom_label_repel调用的副本,但添加一个segment.alpha = 0。然后所有标签将在所有箭头的顶部。

library(ggrepel)
ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
  geom_point(data = df, aes(x=Score, y=Points, colour=Record)) +
  geom_label_repel(data = df,
                   aes(x=Score, y=Points, label = Athletename),
                   direction = "x",
                   nudge_x = -10) +
  geom_label_repel(data = df, 
                   aes(x=Score, y=Points, label = score_and_points), 
                   direction = "y",
                   nudge_y = -200, ) +
  geom_label_repel(data = df, 
                   aes(x=Score, y=Points, label = score_and_points), 
                   direction = "y", segment.alpha = 0,
                   nudge_y = -200, ) +
  scale_y_continuous(name = "Points", 
                     breaks = seq(0,1500,100),
                     limits = c(0,1500)) +
  scale_x_reverse(name = "110m hurdles time (m)",
                  breaks = seq(29,12,-1),
                  limits=c(29,12)) +
  theme(legend.title = element_blank(), legend.position = "top")

enter image description here