Skip to content

contour plot axis correspondence

2 messages · ivo welch, William Dunlap

#
I am struggling with a contour plot.  I want to place a cross over the
minimum.  alas, I don't seem to be able to map axes appropriately.
here is what I mean:

N <- 1000

rm <- rnorm(N, mean=0.0, sd=0.4)
rx <- rnorm(N, mean=0.0, sd=0.4)
rt <- rnorm(N, mean=0.0, sd=0.4)

exploss <- function(hdgM,hdgX) {
    ## this could be any function that is not vectorized
    losscosts <- function(FirmV) { D <- 50; ifelse( FirmV<D, 0.2*(D-FirmV), 0) }
    FirmV <- 100*(1+rt)*(1+rm)*(1+rx) + 100*(hdgM*(1+rm)-hdgM) +
100*(hdgX*(1+rx)-hdgX)
    mean( losscosts( FirmV ) )
}

ss <- seq(-2,0.5,0.1)
MX <- expand.grid( hdgM= ss, hdgX= ss )
MX$z <- unlist(lapply( 1:nrow(MX), function(i) with(MX,
exploss(hdgM[i],hdgX[i])) ))

M <- matrix(MX$z, nrow=length(ss), ncol=length(ss))
rownames(M) <- colnames(M) <- ss

filled.contour( x=ss, y=ss, M )

vline <- function(x, y=c(-99,99), ...) lines(c(x,x), y, ...)
vline(-0.5, col="blue", lwd=3 )


how do I map the -0.5 in the vline() to the true -0.5?  it is drawn .

as a sidenote, it was not easy to figure out how I could plot an z
function for an x-axis and y-axis.  plot(x,y) is very intuitive.  it
would have been nice to have analogous plot3d(x,y,z) and
contour(x,y,z) functions.  as with everything in R, it probably
exists, but I did not find it.  my above code had to map MX (with
x,y,z columns) into a matrix first.

advice appreciated.

best,

/iaw

----
Ivo Welch (ivo.welch at gmail.com)
#
filled.contour() makes two plots (the contour plot and the legend) and
must adjust some par() parameters to do that.  It appears to set them back
to a state where you cannot easily add things to the plot.  There is a trick
mentioned in Stackoverflow a while back about how to use the plot.title
argument to fiddle with filled.contour() plots.  In your case you could do something
like

   > x <- 11:15
   > y <- 101:108
   > z <- outer(x,y,function(x,y)sin(x^2.5+y^.9/1.2))
   > filled.contour(x,y,z, plot.title=abline(v=12, h=103))

If you call abline() after filled.contour you can see how it the horizontal
margin settings do not correspond to the plot you are trying to add to.

   > abline(v=12, h=103, lwd=3, col="red", lty=2)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com