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

时间:2017-06-29 17:42:53

标签: r plot ggplot2 lazy-evaluation roc

我试图用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()和懒惰评估相关。该示例使用了geom_segment(),并且在完全删除aes()后问题得以解决。它对我不起作用,因为我需要以某种方式映射数据。当我在此处删除aes()时,不会绘制任何内容。如何解决依赖于geom_的{​​{1}}中的惰性评估问题?

1 个答案:

答案 0 :(得分:2)

以下是您的代码的工作版本 最终的图形结果不太好,应该加以改进。

allOf

enter image description here