如何使用GGPLOT geom_point()进行选择性标记 [英] How to do selective labeling with GGPLOT geom_point()

查看:533
本文介绍了如何使用GGPLOT geom_point()进行选择性标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p + geom_point() + geom_text(aes(wt, mpg, label=row.names(mtcars)))

我得到了这张图:

如何修改上面的代码,使其仅标记wt > 4mpg > 25的位置, 而其余的点仍未标记.

How can I modify the code above so that it only labels point where wt > 4 or mpg > 25, while the rest of the points remain unlabeled.

推荐答案

geom_text提供一个data参数:

library(ggplot2)
mtcars$name <- row.names(mtcars)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p + geom_point() + 
  geom_text(data=subset(mtcars, wt > 4 | mpg > 25),
            aes(wt,mpg,label=name))

结果图:

PS:我真的不喜欢构建ggplots的p + geom()风格,我很确定hadley在原始ggplot2本书中做了这件事,以演示同一图的不同修改,但是人们似乎选择了启动并运行它.这是我的处理方式:

PS: I'm really not a fan of the p + geom() style of constructing ggplots, I'm pretty sure hadley did it in the original ggplot2 book to demonstrate different modifications of the same plot, but people seem to have picked it up and run with it. Here's how I'd do it:

  • 只需将图的不同组成部分与+一起添加,就不必保存每个中间步骤.
  • 除非确实需要,否则不必费心将其保存到变量中,如果需要,仍可以使用ggsave()
  • 将其保存到文件中.
  • 在第一个ggplot调用中放置将应用于整个情节的所有美学,仅在必要时修改其他内容
  • Just add the different components of the plot together with +, don't save each intermediate step.
  • Don't bother saving it to a variable unless you really need to, you can still save it to a file if you need to with ggsave()
  • Put all the aesthetics that are going to apply to the whole plot in the first ggplot call, only modify the other things if necessary

我的版本:

ggplot(mtcars, aes(wt, mpg, label=name)) +
  geom_point() +
  geom_text(data=subset(mtcars, wt > 4 | mpg > 25))

这篇关于如何使用GGPLOT geom_point()进行选择性标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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