在不同层使用 ggplot2 绘制多条 ROC 曲线

Plot multiple ROC curves with ggplot2 in different layers

我正在尝试使用 ggplot2 在单个图上绘制多条 ROC 曲线。这是我的进展:

ggroc2 <- function(columns, data = mtcars, classification = "am",
                   interval = 0.2, breaks = seq(0, 1, interval)){
  require(pROC)
  require(ggplot2)

  #The frame for the plot
  g <- ggplot() + geom_segment(aes(x = 0, y = 1, xend = 1,yend = 0)) +
    scale_x_reverse(name = "Specificity",limits = c(1,0), breaks = breaks, 
expand = c(0.001,0.001)) + 
    scale_y_continuous(name = "Sensitivity", limits = c(0,1), breaks = 
breaks, expand = c(0.001, 0.001)) +
    theme_classic() + coord_equal()

  #The loop to calculate ROC's and add them as new layers
  for(i in 1:length(columns)){
    croc <- roc(data[,classification], data[,columns[i]]) 
    plotx <- rev(croc$specificities)
    ploty <- rev(croc$sensitivities)
    g <- g + geom_step(aes(x=plotx, y=ploty))
  }

  g
}



#Sample graph
ggroc2(c("mpg", "disp", "drat", "wt"))

问题是只绘制了 columns 列表中的最后一个参数。看完the answer to this question,我确定问题一定与aes()和lazy evaluation有关。该示例使用了 geom_segment(),并且在完全删除 aes() 后问题得到解决。它对我不起作用,因为我需要以某种方式映射数据。当我在这里删除 aes() 时,没有绘制任何内容。如何解决 geom_ 中依赖于 aes() 的惰性求值问题?

这是您的代码的工作版本。
最终的图形效果不太好,有待改进

ggroc2 <- function(columns, data = mtcars, classification = "am",
                   interval = 0.2, breaks = seq(0, 1, interval)){
  require(pROC)
  require(ggplot2)

  #The frame for the plot
  g <- ggplot() + geom_segment(aes(x = 0, y = 1, xend = 1,yend = 0)) +
    scale_x_reverse(name = "Specificity",limits = c(1,0), breaks = breaks, 
expand = c(0.001,0.001)) + 
    scale_y_continuous(name = "Sensitivity", limits = c(0,1), breaks = 
breaks, expand = c(0.001, 0.001)) +
    theme_classic() + coord_equal()

  #The loop to calculate ROC's and add them as new layers
  cols <- palette()
  for(i in 1:length(columns)){
    croc <- roc(data[,classification], data[,columns[i]]) 
    sens_spec <- data.frame(spec=rev(croc$specificities),
                            sens=rev(croc$sensitivities))
    g <- g + geom_step(aes(x=spec, y=sens), data=sens_spec, col=cols[i], lwd=1)
  }
  g
}

#Sample graph
ggroc2(c("mpg", "disp", "drat", "wt"))