1
votes

I am generating multiple plots using lapply to retrieve data from a vector for each of the plots.

Problem:

  • I need to plot the abline for each graph, but it plots only in the last one.
  • Ideally, I would also plot a different title for each of the graphs.

Data:

  • perfs is a vector with 3 elements and each of its elements contains the main data for the plot.
  • Each item in perfs corresponds to a value of k, that has been previously defined in the vector ks = c(5,7,11)

I have tried adding arguments to lapply.

   lapply(perfs, function(perf) {plot(perf, main = paste0("Curva ROC", ks), col = "#42f4bf", lwd = 4)})
   abline(a = 0, b = 1, lwd = 2, lty = 2)

Actual:

  • abline only in the last plot.
  • The title repeated for each of the k in every plot: ROC Curve5 ROC Curve7...
  • This is the last plot: roc_curve_wrong

Expected:

  • Title: ROC Curve 5 ; ROC Curve 7...
  • abline in each graph
2

2 Answers

1
votes

To have the correct title for each plot, you'll need to have a way of linking the elements of perfs to the elements of ks so you can just select the one you need for each plot.
One way to do this (perhaps the simplest) would be to use a for loop, rather than lapply, and use ks[i] in the main parameter of plot. If you prefer to use lapply, then I think match should work fine (as in my code below), provided each of the elements of perfs are different.

To have an abline for each plot, you'll need to include the abline part within the function you call in lapply, so that you run that part alongside each plot.

lapply(perfs, function(perf) {
  k <- ks[match(list(perf), perfs)]     # Only need list() is perfs is a list
  plot(perf, main = paste0("Curve ROC", k), col = "#42f4bf", lwd = 4)
  abline(a = 0, b = 1, lwd = 2, lty = 2)
})
0
votes

I am using a for loop as sugested by @hodgenovice

I use an index ind to access the values of k in the ks vector. This way I can plot the abline for each graph and also name them according to the value of k.

ks <-c(5, 7, 11) # the previously defined values of k

ind <- 1 # index used for accessing ks
for (perf in perfs){  # each perf in perfs contains data used in the plot
     k <- ks[ind]
     ind <- ind + 1
     plot(perf, main = paste0("ROC Curve k = ", k), col = "#42f4bf", lwd = 4) 
     abline(a = 0, b = 1, lwd = 2, lty = 2)
}