为什么geom_text()多次绘制文本? [英] Why is geom_text() plotting the text several times?

查看:156
本文介绍了为什么geom_text()多次绘制文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下最小示例:

library(ggplot2)
library(ggrepel)
ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  geom_text(x = 20, y = 20, label = "(20,20)")

我想您可以很容易地看到文本(20,20)"被过度绘图(实际上,我不知道这是不是正确的词.我的意思是该文本在一个位置多次绘制)

I guess you can see pretty easily that the text "(20,20)" is heavily overplotted (actually, I don't know whether that's the correct word. I mean that the text is plotted several times at one location).

如果我使用annotate(),则不会发生:

If I use annotate(), this does not happen:

ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  annotate("text", x = 20, y = 20, label = "(20,20)")

那么,为什么不使用annotate()?"你可能会问.实际上,我不想使用文本作为注释,而是使用标签.而且我还想使用{ggrepel}包来避免过度绘图.但是看看当我尝试这样做时会发生什么:

"So, why don't you use annotate() then?" you might ask. Actually, I don't want to use text for annotation but labels. And I also want to use the {ggrepel} package to avoid overplotting. But look what happens, when I try this:

ggplot(mtcars) +
  aes(x = mpg, y = qsec) +
  geom_line() +
  geom_label_repel(x = 20, y = 20, label = "(20,20)")

同样,绘制了许多标签,{ggrepel}在防止标签重叠方面做得很好.但我只希望一个标签指向特定位置.我真的不明白为什么会这样.我只为xylabel提供了一个值.我还尝试了data = NULLinherit.aes = F并将值放入geom_label_repel()中的aes()中没有任何作用.我怀疑标签与mtcars中的行一样多.对于我的实际应用程序,这真的很糟糕,因为在相应的数据集中有很多行.

Again, many labels are plotted and {ggrepel} does a good job at preventing them from overlapping. But I want only one label pointing at a specific location. I really don't understand why this happens. I only supplied one value for x, y and label each. I also tried data = NULL and inherit.aes = F and putting the values into aes() within geom_label_repel() to no effect. I suspect that there are as many labels as there are rows in mtcars. For my real application that's really bad because I have a lot of rows in the respective dataset.

您能否在这里帮助我,并简要说明为什么会发生这种情况以及您的解决方案为何起作用?非常感谢!

Could you help me out here and maybe give a short explanation why this happens and why your solution works? Thanks a lot!

推荐答案

geom_textgeom_label_repel每行添加一个标签.因此,您可以为注释几何提交单独的数据集.例如:

geom_text or geom_label_repel adds one label per row. Therefore you can submit a separate dataset for annotation geom. For example:

library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(mpg, qsec)) +
    geom_line() +
    geom_label_repel(aes(20, 20, label = "(20,20)"), data.frame())

这篇关于为什么geom_text()多次绘制文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆