[英]How to get coordinates of a selected point in R plot?
我需要将鼠标指针选择的点传递给R程序坐标,以执行一些计算。 我在使其工作时遇到问题。
我知道这段代码应该标识出图中的点:
plot(kk2$k2,kk2$k1)
identify(kk2$k2,kk2$k1)
但是,即使那样也不行。 在图上显示一些毫无意义的数字,而点具有两个坐标。 为什么?
至少如何解决?
我的目标是使点坐标返回R并对其进行一些计算。 数据集kk2只有两列-k1和k2,仅此而已。
CRAN上提供的“ gatepoints”软件包将允许您绘制一个返回您感兴趣的点的门。
如果您使用的是RStudio,最好先打开一个新的x11设备在一个单独的x11窗口中进行绘制:
X11()
现在绘制您的观点,我已经构成了一些简单的数据:
kk2 <- data.frame(k2=1:10, k1=1:10)
plot(kk2, col = "red", pch = 16)
运行下面的命令,然后通过单击鼠标左键和单击鼠标右键以关闭多边形来选择点:
selectedPoints <- fhs(kk2)
这将返回:
selectedPoints
#> [1] "4" "5" "7"
#> attr(,"gate")
#> k2 k1
#> 1 6.099191 8.274120
#> 2 8.129107 7.048649
#> 3 8.526881 5.859404
#> 4 5.700760 6.716428
#> 5 5.605314 5.953430
#> 6 6.866882 3.764390
#> 7 3.313575 3.344069
#> 8 2.417270 5.217868
locator {graphics} R Documentation
Graphical Input
Description
Reads the position of the graphics cursor when the (first) mouse button is pressed.
![> pts <- locator(4)
> polygon(pts)
> png(); plot(1,1)
> pts <- locator(4)
> polygon(pts)
> dev.off()][1]
尝试这样的操作,因为identify
返回您单击附近的点的seq_along(x)
(称为“一些无意义的数字”):
x <- rnorm(10)
y <- rnorm(10)
plot(x,y)
out <- sapply(list(x,y),"[",identify(x,y))
# do some clicking
out
# something like this is returned for the x/y points
# [,1] [,2]
#[1,] -0.62221766 -0.73838314
#[2,] -0.69896643 0.40186536
#[3,] 0.06077831 -1.63940474
#[4,] -0.09900270 0.00062011
关键是将结果用作索引。 然后可以将其用于识别特定的xy坐标:
n <- 10
x <- runif(n)
y <- runif(n)
df <- data.frame(x=x, y=y)
plot(y ~ x, data=df)
df[identify(x, y, n=1),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.