ggplot 图例问题与 geom_point 和 geom_text
我试图使用geom_point
来说明我的数据计数。我还想用 geom_text
注释图表中的一些点。当我添加对 geom_text 的调用时,它似乎正在图例中的点下方绘制一些内容。我尝试颠倒图层的顺序,但无济于事。我无法理解为什么要这样做。有人见过这个吗?
set.seed(42)
df <- data.frame(x = 1:10
, y = 1:10
, label = sample(LETTERS,10, replace = TRUE)
, count = sample(1:300, 10, replace = FALSE)
)
p <- ggplot(data = df, aes(x = x, y = y, size = count)) + geom_point()
p + geom_text(aes(label = label, size = 150, vjust = 2))
I am trying to use geom_point
to illustrate the count of my data. I would also like to annotate a few of the points in my graph with geom_text
. When I add the call to geom_text
, it appears that it is plotting something underneath the points in the legend. I've tried reversing the order of the layers to no avail. I can't wrap my head around why it is doing this. Has anyone seen this before?
set.seed(42)
df <- data.frame(x = 1:10
, y = 1:10
, label = sample(LETTERS,10, replace = TRUE)
, count = sample(1:300, 10, replace = FALSE)
)
p <- ggplot(data = df, aes(x = x, y = y, size = count)) + geom_point()
p + geom_text(aes(label = label, size = 150, vjust = 2))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种事一直发生在我身上。诀窍在于了解
aes()
将数据映射到美学。如果没有要映射的数据(例如,如果您确定了单个值),则没有理由使用aes()
。我相信只有aes()
内部的内容才会出现在您的图例中。此外,当您在 ggplot(aes()) 内部指定映射时,这些映射将应用于每个后续层。这对您的 x 和 y 有好处,因为
geom_point
和geom_text
都使用它们。这对size = count
不利,因为它仅适用于点。因此,这是我防止此类事情发生的两条规则:
aes()
内部。如果参数采用单个预先确定的值,请将其传递到aes()
的外部层。所以我会这样绘制:
This happened to me all the time. The trick is knowing that
aes()
maps data to aesthetics. If there's no data to map (e.g., if you have a single value that you determine), there's no reason to useaes()
. I believe that only things inside of anaes()
will show up in your legend.Furthermore, when you specify mappings inside of
ggplot(aes())
, those mappings apply to every subsequent layer. That's good for your x and y, since bothgeom_point
andgeom_text
use them. That's bad forsize = count
, as that only applies to the points.So these are my two rules to prevent this kind of thing:
aes()
. If the argument is taking a single pre-determined value, pass it to the layer outside ofaes()
.ggplot(aes())
if you're confident that every subsequent layer will use it. Otherwise, map it at the layer level.So I would plot this thusly:
或者,如果您需要指定 aes 内文本的大小,则 legend = FALSE 禁止绘制几何图例:
or, if you need to specify the size of text inside the aes, then legend = FALSE suppress drawing the legends of the geom: