简体   繁体   English

如何获得R图中选定点的坐标?

[英]How to get coordinates of a selected point in R plot?

I need to pass to R program coordinates of a point selected by the mouse pointer, to perform some calculations. 我需要将鼠标指针选择的点传递给R程序坐标,以执行一些计算。 I have problems getting it to work. 我在使其工作时遇到问题。

I know that this code should identify point on a plot: 我知道这段代码应该标识出图中的点:

plot(kk2$k2,kk2$k1)
identify(kk2$k2,kk2$k1)

But even that doesn't work. 但是,即使那样也不行。 On a plot appears some meaningless number, while point has two coordinates. 在图上显示一些毫无意义的数字,而点具有两个坐标。 why? 为什么?

How to fix at least that? 至少如何解决?

My goal is to have the point coordinates returned to R and perform some calculations on them. 我的目标是使点坐标返回R并对其进行一些计算。 The dataset kk2 has only two columns - k1 and k2, nothing more. 数据集kk2只有两列-k1和k2,仅此而已。

The package "gatepoints" available on CRAN will allow you to draw a gate returning your points of interest. CRAN上提供的“ gatepoints”软件包将允许您绘制一个返回您感兴趣的点的门。

If you are using RStudio it is better to plot in a separate x11 window by first opening a new x11 device: 如果您使用的是RStudio,最好先打开一个新的x11设备在一个单独的x11窗口中进行绘制:

X11()

Now plot your points, I've made up some simple data: 现在绘制您的观点,我已经构成了一些简单的数据:

kk2 <- data.frame(k2=1:10, k1=1:10)
plot(kk2, col = "red", pch = 16)

简单情节

Run the command below and then select your points by left clicking and right clicking to close the polygon: 运行下面的命令,然后通过单击鼠标左键和单击鼠标右键以关闭多边形来选择点:

selectedPoints <- fhs(kk2)

在此处输入图片说明

This will return: 这将返回:

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]

Try something like this, since identify returns the seq_along(x) for the point that you click near (what you refer to as 'some meaningless number'): 尝试这样的操作,因为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

The key is using the result as an index. 关键是将结果用作索引。 This can then be used to identify the specific xy coordinates: 然后可以将其用于识别特定的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM