R語言可視化(三十八):ROC曲線圖繪製

2021-02-13 bioinfomics
38. ROC曲線圖繪製清除當前環境中的變量
rm(list=ls())

設置工作目錄
setwd("C:/Users/Dell/Desktop/R_Plots/38roc/")

使用ROCR包繪製ROC曲線
# 安裝並加載所需的R包
#install.packages("ROCR")
library(ROCR)
## Warning: package 'ROCR' was built under R version 3.6.1
## Loading required package: gplots
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess

# 查看內置示例數據
data(ROCR.simple)
head(ROCR.simple)
## $predictions
## [1] 0.612547843 0.364270971 0.432136142 0.140291078 0.384895941
## [6] 0.244415489 0.970641299 0.890172812 0.781781371 0.868751832
## [11] 0.716680598 0.360168796 0.547983407 0.385240464 0.423739359
## [16] 0.101699993 0.628095575 0.744769966 0.657732644 0.490119891
## [21] 0.072369921 0.172741714 0.105722115 0.890078186 0.945548941
## [26] 0.984667270 0.360180429 0.448687336 0.014823599 0.543533783
## [31] 0.292368449 0.701561487 0.715459280 0.714985914 0.120604738
## [36] 0.319672178 0.911723615 0.757325590 0.090988280 0.529402244
## [41] 0.257402979 0.589909284 0.708412104 0.326672910 0.086546283
## [46] 0.879459891 0.362693564 0.230157183 0.779771989 0.876086217
## [51] 0.353281048 0.212014560 0.703293499 0.689075677 0.627012496
## [56] 0.240911145 0.402801992 0.134794140 0.120473353 0.665444679
## [61] 0.536339509 0.623494622 0.885179651 0.353777439 0.408939895
## [66] 0.265686095 0.932159806 0.248500489 0.858876675 0.491735594
## [71] 0.151350957 0.694457482 0.496513160 0.123504905 0.499788081
## [76] 0.310718619 0.907651100 0.340078180 0.195097957 0.371936985
## [81] 0.517308606 0.419560072 0.865639036 0.018527600 0.539086009
## [86] 0.005422562 0.772728821 0.703885141 0.348213542 0.277656869
## [91] 0.458674210 0.059045866 0.133257805 0.083685883 0.531958184
## [96] 0.429650397 0.717845453 0.537091350 0.212404891 0.930846938
## [101] 0.083048377 0.468610247 0.393378108 0.663367560 0.349540913
## [106] 0.194398425 0.844415442 0.959417835 0.211378771 0.943432189
## [111] 0.598162949 0.834803976 0.576836208 0.380396459 0.161874325
## [116] 0.912325837 0.642933593 0.392173971 0.122284044 0.586857799
## [121] 0.180631658 0.085993218 0.700501359 0.060413627 0.531464015
## [126] 0.084254795 0.448484671 0.938583020 0.531006532 0.785213140
## [131] 0.905121019 0.748438143 0.605235403 0.842974300 0.835981859
## [136] 0.364288579 0.492596896 0.488179708 0.259278968 0.991096434
## [141] 0.757364019 0.288258273 0.773336236 0.040906997 0.110241034
## [146] 0.760726142 0.984599159 0.253271061 0.697235328 0.620501132
## [151] 0.814586047 0.300973098 0.378092079 0.016694412 0.698826511
## [156] 0.658692553 0.470206008 0.501489336 0.239143340 0.050999138
## [161] 0.088450984 0.107031842 0.746588080 0.480100183 0.336592126
## [166] 0.579511087 0.118555284 0.233160827 0.461150807 0.370549294
## [171] 0.770178504 0.537336015 0.463227453 0.790240205 0.883431431
## [176] 0.745110673 0.007746305 0.012653524 0.868331219 0.439399995
## [181] 0.540221346 0.567043171 0.035815400 0.806543942 0.248707470
## [186] 0.696702150 0.081439129 0.336315317 0.126480399 0.636728451
## [191] 0.030235062 0.268138293 0.983494405 0.728536415 0.739554341
## [196] 0.522384507 0.858970526 0.383807972 0.606960209 0.138387070
##
## $labels
## [1] 1 1 0 0 0 1 1 1 1 0 1 0 1 0 0 0 1 1 1 0 0 0 0 1 0 1 0 0 1 1 0 1 1 1 0
## [36] 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 0 0 1 1 1 1 0 0 0 1 0 1 0
## [71] 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 1 1 0 0 1 0 0 1 0 1 0 1 1 0 1 0 0 0 1 0
## [106] 0 1 0 0 1 1 1 0 0 0 1 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 1 0 1 1 0 0 0 0 1
## [141] 1 0 1 0 1 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 0 1 1
## [176] 1 0 1 1 0 1 1 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0

#使用prediction()函數構建prediction對象
pred <- prediction(predictions = ROCR.simple$predictions,
labels = ROCR.simple$labels);
pred

# 不同評估值的計算方法
#ROC curves:
# measure="tpr", x.measure="fpr".
#
#Precision/recall graphs:
# measure="prec", x.measure="rec".
#
#Sensitivity/specificity plots:
# measure="sens", x.measure="spec".
#
#Lift charts:
# measure="lift", x.measure="rpp".

# 計算ROC值並繪製ROC曲線
## computing a simple ROC curve (x-axis: fpr, y-axis: tpr)
perf <- performance(prediction.obj = pred,
measure = "tpr",
x.measure = "fpr")
perf

plot(perf,colorize=TRUE,
main="ROCR fingerpainting toolkit",
xlab="Mary's axis", ylab="",
box.lty=7, box.lwd=2, box.col="gray")

image.png
## 計算曲線下的面積即AUC值
auc<-  performance(pred,"auc")
auc
## An object of class "performance"
## Slot "x.name":
## [1] "None"
## 
## Slot "y.name":
## [1] "Area under the ROC curve"
## 
## Slot "alpha.name":
## [1] "none"
## 
## Slot "x.values":
## list()
## 
## Slot "y.values":
## [[1]]
## [1] 0.8341875
## 
## 
## Slot "alpha.values":
## list()

auc_area<-slot(auc,"y.values")[[1]]
# 保留4位小數
auc_area<-round(auc_area,4)
#添加文本注釋
text_auc<-paste("AUC=", auc_area,sep="")
text(0.25,0.9,text_auc)

image.png
## precision/recall curve (x-axis: recall, y-axis: precision)
perf1 <- performance(pred, "prec", "rec")
plot(perf1,colorize=T)

image.png
## sensitivity/specificity curve (x-axis: specificity, y-axis: sensitivity)
perf1 <- performance(pred, "sens", "spec")
plot(perf1,colorize=T)

image.png使用pROC包繪製ROC曲線圖
#安裝並加載所需的R包
#install.packages("pROC")
library(pROC)
## Warning: package 'pROC' was built under R version 3.6.3
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.6.3

# 查看內置數據集
data("aSAH")
head(aSAH)
## gos6 outcome gender age wfns s100b ndka
## 29 5 Good Female 42 1 0.13 3.01
## 30 5 Good Female 37 1 0.14 8.54
## 31 5 Good Female 42 1 0.10 8.09
## 32 5 Good Female 27 1 0.04 10.42
## 33 1 Poor Female 42 3 0.13 17.40
## 34 1 Poor Male 48 2 0.10 12.75

# 使用roc()函數計算ROC值並繪製ROC曲線
#roc(aSAH$outcome ~ aSAH$s100b)
roc.s100b <- roc(outcome ~ s100b, aSAH, levels=c("Good", "Poor"))
## Setting direction: controls < cases
roc.s100b
##
## Call:
## roc.formula(formula = outcome ~ s100b, data = aSAH, levels = c("Good", "Poor"))
##
## Data: s100b in 72 controls (outcome Good) < 41 cases (outcome Poor).
## Area under the curve: 0.7314

# 繪製基礎ROC曲線
plot(roc.s100b)

image.png
# 添加平滑ROC曲線
# Add a smoothed ROC:
plot(smooth(roc.s100b), add=TRUE, col="blue")
# 添加圖例
legend("topright", legend=c("Empirical", "Smoothed"),
       col=c(par("fg"), "blue"), lwd=2)

image.png
# 添加一些參數美化ROC曲線
plot(roc.s100b, 
     print.auc=TRUE, #設置是否添加AUC值標籤
     auc.polygon=TRUE, #設置是否添加AUC值面積多邊形
     max.auc.polygon=TRUE, #設置是否添加最大AUC值面積多邊形
     auc.polygon.col="skyblue", #設置AUC值面積多邊形的填充色
     grid=c(0.1, 0.2), #添加網格線
     grid.col=c("green", "red"), #設置網格線顏色
     print.thres=TRUE)

image.png
# To plot a different partial AUC, we need to ignore the existing value
# with reuse.auc=FALSE:
plot(roc.s100b, print.auc=TRUE, auc.polygon=TRUE, 
     partial.auc=c(1, 0.8), # 計算選定範圍的AUC值
     partial.auc.focus="sp", # 高亮關注選定範圍的AUC值
     grid=c(0.1, 0.2), grid.col=c("green", "red"),
     max.auc.polygon=TRUE, auc.polygon.col="lightblue", 
     print.thres=TRUE, print.thres.adj = c(1, -1),
     reuse.auc=FALSE)

image.png
roc.wfns <- roc(aSAH$outcome, aSAH$wfns)
## Setting levels: control = Good, case = Poor
## Setting direction: controls < cases

roc.ndka <- roc(aSAH$outcome, aSAH$ndka)
## Setting levels: control = Good, case = Poor
## Setting direction: controls < cases

# Add a second ROC curve to the previous plot:
plot(roc.s100b, col="red")
plot(roc.wfns, col="blue", add=TRUE)
plot(roc.ndka, col="green", add=TRUE)

image.png
# 使用ggcor()函數繪製基於ggplot2的ROC曲線
ggroc(roc.s100b, 
      alpha = 0.5, colour = "red", 
      linetype = 2, size = 2) +
  theme_minimal() + 
  ggtitle("My ROC curve") + 
  geom_segment(aes(x = 1, xend = 0, y = 0, yend = 1), 
               color="grey", linetype="dashed")

image.png
# 繪製多條ROC曲線
# Multiple curves:
ggroc(list(s100b=roc.s100b, wfns=roc.wfns, ndka=roc.ndka))

image.png
# This is equivalent to using roc.formula:
roc.list <- roc(outcome ~ s100b + ndka + wfns, data = aSAH)
## Setting levels: control = Good, case = Poor
## Setting direction: controls < cases
## Setting levels: control = Good, case = Poor
## Setting direction: controls < cases
## Setting levels: control = Good, case = Poor
## Setting direction: controls < cases

g.list <- ggroc(roc.list, aes=c("linetype", "color"))
g.list

image.png
# 分面展示
# OR faceting
g.list + facet_grid(.~name) + 
  theme_bw() 

image.png使用survivalROC包繪製時間依賴的ROC曲線
# 安裝並加載所需的R包
#install.packages("survivalROC")
library(survivalROC)

# 查看內置數據集
data(mayo)
head(mayo)
## time censor mayoscore5 mayoscore4
## 1 41 1 11.251850 10.629450
## 2 179 1 10.136070 10.185220
## 3 334 1 10.095740 9.422995
## 4 400 1 10.189150 9.567799
## 5 130 1 9.770148 9.039419
## 6 223 1 9.226429 9.033388

# 計算數據的行數
nobs <- NROW(mayo)
nobs
## [1] 312

# 自定義閾值
cutoff <- 365

# 使用MAYOSCORE 4作為marker, 並用NNE(Nearest Neighbor Estimation)法計算ROC值
Mayo4.1 = survivalROC(Stime=mayo$time,
status=mayo$censor,
marker = mayo$mayoscore4,
predict.time = cutoff,
span = 0.25*nobs^(-0.20) )
Mayo4.1

# 繪製ROC曲線
plot(Mayo4.1$FP, Mayo4.1$TP, type="l",
xlim=c(0,1), ylim=c(0,1), col="red",
xlab=paste( "FP", "\n", "AUC = ",round(Mayo4.1$AUC,3)),
ylab="TP",main="Mayoscore 4, Method = NNE \n Year = 1")
# 添加對角線
abline(0,1)

image.png
# 使用KM(Kaplan-Meier)法計算ROC值
## MAYOSCORE 4, METHOD = KM
Mayo4.2= survivalROC(Stime=mayo$time,  
                     status=mayo$censor,      
                     marker = mayo$mayoscore4,     
                     predict.time =  cutoff, method="KM")
Mayo4.2

plot(Mayo4.2$FP, Mayo4.2$TP, type="l", 
     xlim=c(0,1), ylim=c(0,1), col="blue",
     xlab=paste( "FP", "\n", "AUC = ",round(Mayo4.2$AUC,3)), 
     ylab="TP",main="Mayoscore 4, Method = KM \n Year = 1")
abline(0,1,lty=2,col="gray")

image.png
# 將兩種方法的結果繪製到同一個圖裡
## 繪製NNE法計算的ROC曲線
plot(Mayo4.1$FP, Mayo4.1$TP,
     type="l",col="red",
     xlim=c(0,1), ylim=c(0,1),   
     xlab="FP", 
     ylab="TP",
     main="Time dependent ROC")
# 添加對角線
abline(0,1,col="gray",lty=2)

## 添加KM法計算的ROC曲線
lines(Mayo4.2$FP, Mayo4.2$TP, 
      type="l",col="blue",
      xlim=c(0,1), ylim=c(0,1))
# 添加圖例
legend("bottomright",legend = c(paste("AUC of NNE =",round(Mayo4.1$AUC,3)),
                          paste("AUC of KM =",round(Mayo4.2$AUC,3))),
       col=c("red","blue"),
       lty= 1 ,lwd= 2)

image.png
sessionInfo()
## R version 3.6.0 (2019-04-26)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 18363)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936
## [2] LC_CTYPE=Chinese (Simplified)_China.936
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C
## [5] LC_TIME=Chinese (Simplified)_China.936
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] survivalROC_1.0.3 ggplot2_3.3.2 pROC_1.16.2 ROCR_1.0-7
## [5] gplots_3.0.1.1
##
## loaded via a namespace (and not attached):
## [1] Rcpp_1.0.5 compiler_3.6.0 pillar_1.4.2
## [4] plyr_1.8.4 bitops_1.0-6 tools_3.6.0
## [7] digest_0.6.20 evaluate_0.14 tibble_2.1.3
## [10] lifecycle_0.2.0 gtable_0.3.0 pkgconfig_2.0.2
## [13] rlang_0.4.7 yaml_2.2.0 xfun_0.8
## [16] withr_2.1.2 stringr_1.4.0 dplyr_1.0.2
## [19] knitr_1.23 generics_0.0.2 vctrs_0.3.2
## [22] gtools_3.8.1 caTools_1.17.1.2 grid_3.6.0
## [25] tidyselect_1.1.0 glue_1.4.2 R6_2.4.0
## [28] rmarkdown_1.13 gdata_2.18.0 purrr_0.3.2
## [31] magrittr_1.5 scales_1.0.0 htmltools_0.3.6
## [34] colorspace_1.4-1 labeling_0.3 KernSmooth_2.23-15
## [37] stringi_1.4.3 munsell_0.5.0 crayon_1.3.4

相關焦點

  • 基於R、Python和SPSS繪製ROC曲線並計算AUC
    ROC和AUC基於上述指標,我們可以利用ROC(Receiver Operating Characteristic) 曲線可視化分類效果。對於任一分類閾值,我們都可以得到一組取值(真陽性率,假陽性率)。
  • 畫ROC曲線的R包總結
    //rviews.rstudio.com/2019/03/01/some-r-packages-for-roc-curves/在這篇文章中,我將描述如何在CRAN中搜索繪製ROC曲線的包,並強調六個有用的包。
  • R語言可視化(十八):UMAP圖繪製
    UMAP圖繪製清除當前環境中的變量rm(list=ls())設置工作目錄setwd("C:/Users/Dell/Desktop/R_Plots/18umap/")查看示例數據head(iris)[,2]## [1,] 12.59949 3.759360## [2,] 13.80894 5.272737## [3,] 14.43500 4.813293## [4,] 14.36174 4.896541## [5,] 12.80543 3.473356## [6,] 12.14902 2.715970# 使用plot函數可視化
  • 手把手教你用R繪製生存曲線圖
    好的生存曲線圖不僅可以令讀者、編輯和審稿專家眼前一亮,也能為論文增色不少。接下來跟大家分享如何用R語言繪製生存曲線圖。survival包對生存數據進行建模.survfit()函數來估計刪失數據的生存曲線;coxph()函數用來擬合Cox比例風險模型.
  • R語言可視化學習筆記之ggridges包繪製山巒圖
    作者:嚴濤 浙江大學作物遺傳育種在讀研究生(生物信息學方向)偽碼農,R語言愛好者,愛開源。
  • 醫學統計與R語言:隨機森林與Logistic預測(randomForest vs Logistic regression)
    <- roc(Smoking_status~testdata$probran[,1], data = testdata,smooth=F)roc.test(g,r)Bootstrap test for two correlated ROC curvesdata:  g and rD = -1.0468, boot.n = 2000,
  • R語言繪製條形圖
    熟悉R語言的用戶應該都可以熟練的繪製條形圖,但在實際應用中,我們常常會根據數據展示的需求對條形圖進行調整,這就需要我們花費大量時間了解條形圖繪製函數的一些參數及高級方法。基於此,本文整理出一些常用的條形圖繪製代碼,希望可以為大家帶來一些方便。
  • Python-Matplotlib 動態曲線圖繪製
    引言動態曲線圖不同於動態氣泡圖,它可以查看部分指標在一段時間內的變化趨勢,本期推文將推出動態曲線圖的 Matplotlib 繪製過程,核心過程為 折線圖 和 散點圖 的繪製,詳細過程如下:02.數據可視化動態圖表的繪製主要在於折線圖和散點圖的繪製,我們採用的依舊還是面向對象式繪圖方式,這裡建議繪製較為複雜的圖表時多採用此方法進行繪製。
  • 基於R語言PredictABEL包對Logistic回歸模型外部驗證
    <- sum(pihatcat==i)*meanprobs[i,2] obsevents[i,2] <- sum(1-y[pihatcat==i])}計算 Hosmer-Lemeshow 檢驗統計量。
  • R語言可視化(二):折線圖繪製
    02.折線圖繪製清除當前環境中的變量rm(list=ls())設置工作目錄setwd("C:/Users/Dell
  • 中了數據可視化的毒:BBC如何使用R語言繪製數據圖表?
    BBC(英國廣播公司)近日分享了他們的視覺與數據新聞團隊使用 R 語言繪製新聞圖表的經驗。為了簡化流程,他們創建了一個 bbplot 軟體包和一份參考手冊,並也已將它們開源。過去一年裡,BBC 視覺與數據新聞(Visual and Data Journalism)團隊的數據記者已經從根本上改變了他們繪製發表在 BBC 新聞網站上的數據圖表的方式。
  • R語言學習筆記之相關性矩陣分析及其可視化
    rcorr(x, type = c(「pearson」,「spearman」))。library(Hmisc)#加載包res2 <- rcorr(as.matrix(mydata))res2#可以用res2$r、res2$P來提取相關係數以及顯著性p-valueres2$r
  • 運維丨Python中ROC曲線繪製
    首先以支持向量機模型為例先導入需要使用的包,我們將使用roc_curve這個函數繪製ROC曲線!
  • R語言、Matlab、MeteoInfo、Python及ArcGis可視化DEM地形圖
    一、R語言可視化DEM地形圖-往期推文超連結:1
  • R語言可以這麼玩 | 繪製地圖與地點數據可視化
    這次,我們用R來畫地圖吧,利用可視化工具,我們更能輕鬆地得出結論哦~R語言裡的ggmap包是繪製地圖的利器。在確保電腦可以上外網的情況下(為了保證進入google地圖的URL),ggmap包幫助我們輕鬆下載google map,再加上和ggplot2製圖包的疊加,可以輕鬆、方便地繪製可視化地圖。
  • R語言可視化(二十四):和弦圖繪製
    和弦圖繪製清除當前環境中的變量rm(list=ls())設置工作目錄setwd("C:/Users/Dell/Desktop/R_Plots/24chord/")使用circlize包繪製和弦圖# 安裝並加載所需的
  • R與生物專題 | 第五十講 R-ROC曲線
    我們就需要用到ROC曲線來幫助大家找到最好的診斷切點,用以定義診斷試驗/預測模型的最佳狀態。 曲線下面積(Area under the Curve of ROC (AUCROC))總結了預測模型的整體性能,在比較不同的分類模型時,可以將每個模型的ROC曲線都畫出來,比較曲線下面積做為模型優劣的指標。它表示預測模型區分事件與非事件的能力。
  • 多元數據Andrews曲線繪圖實例及R語言實現
    圖1 實例數據R語言中繪製Andrews曲線的函數很多,本文採用MSG程序包的andrews_curve函數繪製調和曲線。其他參數與R語言自帶的plot函數相同。andrews_curve函數會對每個樣品的p個指標,根據andrews表達式,繪製一條二維曲線。本例有27個樣品,故andrews曲線圖會包含27條曲線。
  • R語言可視化(二十九):聚類樹圖繪製
    聚類樹圖繪製清除當前環境中的變量rm(list=ls())設置工作目錄setwd("C:/Users/Dell/Desktop/R_Plots/29dendrogram/")使用dendrogram函數繪製聚類樹圖
  • Day7:R語言課程 (R語言進行數據可視化)
    學習目標使用擴展包「ggplot2」繪製圖表。使用「map」函數進行數據結構迭代。導出在R環境之外使用的圖片。1.設置數據框以進行可視化在本課中需要製作與每個樣本中的平均表達量相關的多個圖,還需要使用所有可用的metadata來適當地注釋圖表。觀察rpkm數據。