R:使用 ROCR 绘制多条不同颜色的 ROC 曲线

R: Plot multiple different coloured ROC curves using ROCR

以下代码摘自@adibender 对 "Multiple ROC curves in one plot ROCR" 的回答。代码部分来自?plot.performance.

library(ROCR)
data(ROCR.simple)
preds <- cbind(p1 = ROCR.simple$predictions, 
            p2 = abs(ROCR.simple$predictions + 
            rnorm(length(ROCR.simple$predictions), 0, 0.1)))

pred.mat <- prediction(preds, labels = matrix(ROCR.simple$labels, 
            nrow = length(ROCR.simple$labels), ncol = 2) )

perf.mat <- performance(pred.mat, "tpr", "fpr")
plot(perf.mat)

我想在单个图中说明多条 ROC 曲线,如上面的代码,使用 r 包 ROCR。但是,我希望 ROC 曲线具有不同的颜色。如何将不同的颜色应用于不同的曲线?提前致谢。

ROCR 对象的 plot 函数似乎不提供此选项。因此,您必须将物体拆开并手动完成。

例如,使用ggplot2

library(ggplot2)
df <- data.frame(Curve=as.factor(rep(c(1,2), each=length(perf.mat@x.values[[1]]))), 
                 FalsePositive=c(perf.mat@x.values[[1]],perf.mat@x.values[[2]]),
                 TruePositive=c(perf.mat@y.values[[1]],perf.mat@y.values[[2]]))
plt <- ggplot(df, aes(x=FalsePositive, y=TruePositive, color=Curve)) + geom_line()
print(plt)

试试这个(你可以用 ROCR 来做):

library(ROCR)
data(ROCR.simple)
preds <- cbind(p1 = ROCR.simple$predictions, 
               p2 = abs(ROCR.simple$predictions + 
                          rnorm(length(ROCR.simple$predictions), 0, 0.1)))
n <- 2 # you have n models
colors <- c('red', 'blue') # 2 colors
for (i in 1:n) {
   plot(performance(prediction(preds[,i],ROCR.simple$labels),"tpr","fpr"), 
                                           add=(i!=1),col=colors[i],lwd=2)
}

您可以只使用 plot with add=TRUE

pred <- prediction( predicted1, response )
pred2 <- prediction(predicted2, response)
perf <- performance( pred, "tpr", "fpr" )
perf2 <- performance(pred2, "tpr", "fpr")
plot( perf, colorize = FALSE,  type="l",col="blue")
abline(a=0,b=1)
plot(perf2,colorize = FALSE, add = TRUE,  type="l", lty=3,col="black")