如何排斥ggplot中的标签

How to repel labels in ggplot

如果下面示例中的标签重叠,我们如何实现排斥选项?谢谢!

means <- df %>% 
  group_by(cyl) %>% 
  summarize(across(c(wt, mpg), mean))
ggplot(df)  +
  aes(x=wt, y=mpg, color=cyl, shape=cyl) + 
  geom_point() + 
  geom_point(size=4, data=means) + 
  geom_label(aes(label=cyl), color="black", data=means) -> fig
fig

如果我从 ggrepel package

添加 geom_label_repel()
 fig + geom_label_repel()

我收到错误:

geom_label_repel requires the gollowing missing aesthetics: label

您需要映射 label 以便 geom_label_repel“看到”它。它没有来自其他几何体的映射的直接视图。只是它本身和顶部 ggplot 调用。因此,您有两个选择。

直接在函数内

geom_label_repel(mapping = aes(label = cyl))

或者在上面ggplot调用

ggplot(data = df, mapping = aes(label = cyl)) +

请注意,如果您想标记 means 点,您可能必须指定 data,如评论中提到的 Vincent。