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

标签 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_ 中依赖于 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"))

enter image description here

关于r - 在不同层使用 ggplot2 绘制多条 ROC 曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831753/

相关文章:

r - 用R解析ISO8601日期和时间格式

java - 错误 : unable to load installed packages just now

r - Shiny 动态添加输入字段和数据而无需重新渲染

python - 绘制离散变量随时间变化的图(围巾图)

r - 无法使用ggplot2在瀑布图中添加数据标签

r:将变量名作为字符串传递

r - 根据R中的id组合行

javascript - 用于 plotly.js 图表的 React 和包装器

python - 在Python中绘制热图

python - 来自 Python 计数表的箱线图