User function outline in R

I work with some custom functions, and I need to draw outlines for them based on several parameter values.

Here is an example function:

enter image description here

I need to draw a contour graph like this:

enter image description here

Any idea?

Thanks.

+10
r plot contour
source share
2 answers

First, you create a fourvar function that takes these four parameters as arguments. In this case, you could do this with three variables, one of which was lambda_2 over lambda_1. Alpha1 is fixed at 2, so alpha_1 / alpha_2 will vary between 0-10.

 fourvar <- function(a1,a2,l1,l2){ a1* integrate( function(x) {(1-x)^(a1-1)*(1-x^(l2/l1) )^a2} , 0 , 1)$value } 

The trick is to understand that the integrate function returns a list, and you only want the โ€œvalueโ€ part of this list so that it can be Vectorize() -ed.

Secondly, you create a matrix using this function:

  mat <- outer( seq(.01, 10, length=100), seq(.01, 10, length=100), Vectorize( function(x,y) fourvar(a1=2, x/2, l1=2, l2=y/2) ) ) 

Then the task of creating a graph with labels in these positions can be easily done only with lattice::contourplot . After a reasonable search, it seems that the geom_contour labeling solution is still ongoing in ggplot2. The only labeling strategy I have found is an external package. However, the directlabels feature of directlabel does not seem to have enough control to correctly distribute labels in this case. In the other examples that I saw, it spreads labels around the chart area. I suppose I could look at the code, but since it depends on the โ€œproto-packageโ€, it will probably be confusing, so I did not look.

 require(reshape2) mmat <- melt(mat) str(mmat) # to see the names in the melted matrix g <- ggplot(mmat, aes(x=Var1, y=Var2, z=value) ) g <- g+stat_contour(aes(col = ..level..), breaks=seq(.1, .9, .1) ) g <- g + scale_colour_continuous(low = "#000000", high = "#000000") # make black install.packages("directlabels", repos="http://r-forge.r-project.org", type="source") require(directlabels) direct.label(g) 

Note that these are index positions from the matrix, not parameter relations, but this should be fairly easy to fix.

enter image description here

On the other hand, how easy it is to build it in a grid (and I think it looks โ€œcleanerโ€:

  require(lattice) contourplot(mat, at=seq(.1,.9,.1)) 

enter image description here

+15
source share

Since I think the question is still relevant, there have been some changes in the labeling of the metR contour metR package. Adding to the previous example will give you good outline marking also with ggplot2

 require(metR) g + geom_text_contour(rotate = TRUE, nudge_x = 3, nudge_y = 5) 

Labeled contour plot

0
source share

All Articles