簡體   English   中英

如何獲得R圖中選定點的坐標?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM