Reputation: 28907
I have an R plot and I'd like the user to be able to click a spot on the graph, and I'd like to know where they clicked. Sort of like a mouse listener. I'm using RStudio. Is this possible in any way? Basically, for a point they click on, I want to display another plot with more details about that point.
Here's what I have:
data <- data.frame(x=c(1,2,3,4,5),y=c(1,2,3,4,5))
x11()
plot(data)
loc <- locator(n=1)
if(loc$x > 2) {
x11()
plot(c(1,2,3),c(5,6,7))
}
loc <- locator(n=1)
if(loc$x > 2) {
x11()
plot(c(4,5,6),c(5,6,7))
}
So, the first plot comes up that has 5 data points. If the user clicks past an x value of 2, then I want to open another plot, which plots the data points you see listed (3 data points). Then, if they close that plot and they click past 2 AGAIN on the original, 5 data point plot, then I want it to open up a new plot with the 3 data points you see in the second if statement.
But it's giving me errors and I/O issues.
Upvotes: 3
Views: 3155
Reputation: 8061
This works fine in RStudio if you perform the locator()
call against the built-in plots pane. I think it's calling locator
against X11 that causes the problems in RStudio. After plotting the X11 detail info, call dev.set(0)
to make the RStudio plots pane active again.
data <- data.frame(x=c(1,2,3,4,5),y=c(1,2,3,4,5))
plot(data)
loc <- locator(n=1)
if(loc$x > 2) {
x11()
plot(c(1,2,3),c(5,6,7))
}
dev.set(0)
loc <- locator(n=1)
if(loc$x > 2) {
x11()
plot(c(4,5,6),c(5,6,7))
}
(To be honest, I'm not sure why dev.set(0)
works, would have to check with the developer who wrote the RStudio graphics device.)
Upvotes: 0
Reputation: 263352
(I realize this is not a complete answer but it wouldn't format very well as a comment.) To make a particular device the active device you need to determine its number. After executing your code, I can get my list of devices and set the first X11 device to be current
dev.list()
#quartz X11 quartz X11 X11
# 2 3 4 5 6
dev.set(3)
#X11
# 3
So try this:
x11() ; first.ID <- dev.cur()
plot(data)
loc <- locator(n=1)
if(loc$x > 2) {
x11() ; second.ID <- dev.cur()
plot(c(1,2,3),c(5,6,7))
}
dev.set(first.ID)
loc <- locator(n=1)
if(loc$x > 2) {
x11() ; third.ID <- dev.cur()
plot(c(4,5,6),c(5,6,7))
}
On my machine you need to also click on the first graphics window's title to expose it because the Mac Gui does not bring the active device to the foreground.
Upvotes: 3