【问题标题】:Plot multiple ROC curves with ggplot2 in different layers [duplicate]在不同的层中用ggplot2绘制多条ROC曲线[重复]
【发布时间】:2017-12-03 13:05:48
【问题描述】:

我正在尝试使用 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() 的惰性求值问题?

【问题讨论】:

  • This answer 显示使用变量名和aes_string 作为解决方法。
  • 关于重复问题,感谢指出。我正在尝试决定是否应该单击“这解决了我的问题!”按钮,或“我将编辑以解释如何”。我的问题似乎确实是重复的,但我发现下面的答案比将我的数据重塑为长格式更优雅和有效的解决方法。我该怎么办?
  • 我选择它作为副本与其他副本的原因之一是它显示了data.frame 解决方法。这里给出的答案是使用相同的方法。

标签: r plot ggplot2 lazy-evaluation roc


【解决方案1】:

这是您的代码的工作版本。
最终的图形效果不是很好,应该改进。

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"))

【讨论】:

  • "最终的图形效果不太好,应该改进。"你指的是重叠线吗?无论如何,非常示范性的答案,谢谢。我非常清楚地理解它。从这里开始应该很容易。
  • @naco 是的,我不喜欢重叠的线条。无论如何,我很高兴您发现我的回答很有帮助!
猜你喜欢
  • 2019-02-27
  • 2017-06-19
  • 1970-01-01
  • 2017-06-09
  • 2021-03-03
  • 1970-01-01
  • 2019-09-16
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多