有什么办法可以用ggplot 2来使用Identify命令吗? [英] Is there any way to use the Identify command with ggplot 2?

查看:227
本文介绍了有什么办法可以用ggplot 2来使用Identify命令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,一切正常:

In this case, everything is ok:

x <- 1:10 
y <- x^3
plot(x, y)
identify(x, y)

但是,使用qplot有一些麻烦:

But, using qplot there are some troubles:

x <- 1:10 
y <- x^3
qplot(x, y)
identify(x, y)

是否有人知道类似的命令或其他方式来标记ggplot2图中的特定点?

Does anybody know a similar command or other way to label specific points in ggplot2 graphs?

推荐答案

这是一种仅使用网格 ggplot2 包:

Here is a method that works using only the grid and ggplot2 packages:

library(ggplot2)
library(grid)

x <- 1:10  
y <- x^3 
qplot(x, y) 

downViewport('panel-3-4')
pushViewport(dataViewport(x,y))

tmp <- grid.locator('in')
tmp.n <- as.numeric(tmp)
tmp2.x <- as.numeric(convertX( unit(x,'native'), 'in' ))
tmp2.y <- as.numeric(convertY( unit(y,'native'), 'in' ))

w <- which.min( (tmp2.x-tmp.n[1])^2 + (tmp2.y-tmp.n[2])^2 )
grid.text(w, tmp$x, tmp$y )

如果你想要一个文本标签而不是你可以在 grid.text 的调用中替换 w ,例如字母[ w] (或任何你想要的标签向量)。

If you want a text label instead of the number your could replace w in the call to grid.text with something like letters[w] (or whatever vector of labels you want).

如果你打算做几个这样的事情,那么你可以包装它一个函数最后几行可能在一个循环中。你也可以添加附加逻辑来警告,如果你不点击一个点附近(比如识别),或者将标签移近或者离点更近(这个版本将标签放在最近的数据点的标签点上) 。

If you are going to be doing several of these then you could wrap this in a function with the last few lines possibly in a loop. You could also add addtional logic to warn if you don't click near a point (like identify does) or to move the label closer or further from the point (this version places the label for the nearest datapoint at the point that you click).

这篇关于有什么办法可以用ggplot 2来使用Identify命令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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