Use the "directlabels" package to select selection curves

I have a dataset to which I have applied a nonlinear model. The data and model were subsequently plotted in "R" using the "ggplot2" package, so that the data and the model occupy the same ggplot. The model was built for a number of different (free) parameter values, and I want to label each of the resulting curves according to which parameter value created them. However, when I use the "directlabels" package for this, I end up marking the curves of the model as well as the raw data.

To illustrate this problem a little more simply, I created the following code that creates three labeled curves, I would like to know if there is a way to label two (or one) of the three. I am completely new to using ggplot2, so it is possible that I am overusing "ggplot" or "directlabels". Any help you can provide would be greatly appreciated.

The code looks like this:


    # 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")



source to share

1 answer

I don't know if there is a less clunky way, but one solution would be to change the unsaturated 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 only gives me labels 2 and 4, and 0 (red line) remains unlabeled.



All Articles