Roland
Roland

Reputation: 537

Adding Points to filled.contour in R - at the right place

I'd like to add a point to an existing filled.contour plot, using the following code:

MyFunction <- function(x,y){
   return(dnorm(sqrt(x^2+y^2)))
}
wrapper <- function(x, y, my.fun, ...) {sapply(seq_along(x), FUN = function(i) my.fun(x[i], y[i], ...))}
meshstep <- 0.5
x<- seq(-20,20,meshstep)
y <-seq(-20,20,meshstep)
z <- outer(x,y,FUN = wrapper, my.fun=MyFunction)
filled.contour(x,y,z, col=rev(heat.colors(n=20, alpha=0.7)), nlevels=15)
points(0,0)

I'm pretty surprised that points(0,0) didn't put a point into the origin of the plot, but roughly located at x=10,y=0. Also, locator() seems to be prompting coordinates with respect to that 'new' coordinate system as well. Why is that?

Upvotes: 7

Views: 7284

Answers (2)

Greg Snow
Greg Snow

Reputation: 49650

The best option is to use the plot.axes argument as mentioned by @juba. But, if you really need to add something after the plot has finished then you can use locator to click on 2 points in the plot where you know the values of the points in the coordinate system you want to use (opposite corners), then use the updateusr function from the TeachingDemos package to modify the current coordinate system to the one that you want to use. You can then add to the plot using the new coordinate system (you may need to set par(xpd=NA)).

Upvotes: 2

juba
juba

Reputation: 49033

You can find a detailed answer here : Plotting a box within filled.contour plots in R?

In short, filled.contour use two different coordinates system, one for the filled contour and one for the legend. To solve your problem, you either have to use another function, or to put your points into the plot.axes argument :

filled.contour(x,y,z, col=rev(heat.colors(n=20, alpha=0.7)), nlevels=15,
               plot.axes={points(0,0)})

enter image description here

Upvotes: 4

Related Questions