frank2165
frank2165

Reputation: 114

Use 'directlabels' package to label select curves

I have a dataset to which I have fit a nonlinear model. The data and the model have been subsequently plotted in 'R' using the package 'ggplot2', such that the data and the model occupy the same ggplot. The model has been plotted for a range of different (free) parameter values and I wish to label each of the resulting curves according to which parameter value has generated them. However when I use the 'directlabels' package to do this I end up labelling the model curves as well as the raw data.

To illustrate this problem a little more simply I've created the following code that produces three labelled curves, I would like to know if there's a way to label two (or one) out of the three. I'm quite new to using ggplot2, so It's entirely possible that I'm misusing 'ggplot' or 'directlabels'. Any help you can provide would be greatly appreciated.

Code is as follows:

    require("ggplot2")
    require("reshape2")
    require("directlabels")

    # Test function
    f <- function(x,y){
    x^2 + y^2
    }

    # Define range of values for each variable
    X <- seq(-4,4,0.1)
    Y <- seq(0,4,2)

    ## Label all curves:
    # Create data frame
    M <- lapply(Y, f, X)
    names(M) = Y

    M <- melt(M, id.vars = "Y")
    M <- cbind(M,X)
    names(M) = c("value", "Y", "X")

    # Plot (x, f(x,y)) for each value of y.
    p <- ggplot(M, aes(x = X, y = M$value)) + 
    geom_line(aes(y = M$value, color = M$Y), group = M$Y)
    p <- p + geom_dl(aes(label = M$Y),  method = "top.bumpup")
    p

Upvotes: 3

Views: 310

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70623

I don't know if there's a less clunky way, but one solution would be to change the non-relevant labels to NA, save it to a new variable and plot it.

newvar <- ifelse(M$Y == 0, NA, M$Y)
p + geom_dl(aes(label = newvar),  method = "top.bumpup")

This gives me only labels 2 and 4, while 0 (red line) remains unlabelled.

Upvotes: 1

Related Questions