ргдшщ
ргдшщ

Reputation: 83

R ggplot add new roc curve

I want to add an ROC curve to a ggplot chart, but it returns an error code.

  library(ggplot2)
  library(plotROC)

  set.seed(2529)
  D.ex <- rbinom(200, size = 1, prob = .5)
  M1 <- rnorm(200, mean = D.ex, sd = .65)
  M2 <- rnorm(200, mean = D.ex, sd = 1.5)

  test <- data.frame(D = D.ex, D.str = c("Healthy", "Ill")[D.ex + 1], 
                     M1 = M1, M2 = M2, stringsAsFactors = FALSE)
  plot<-ggplot(longtest, aes(d = D, m = M1 )) + geom_roc() + style_roc()
  plot

its ok, but if im add new ROC line its return error

plot<-ggplot(longtest, aes(d = D, m = M1 )) + geom_roc() + style_roc()
plot+ggplot(test, aes(d = D, m = M2)) + geom_roc()

Error in p + o : non-numeric argument to binary operator In addition: Warning message: Incompatible methods ("+.gg", "Ops.data.frame") for "+"

How i can add new line and color all line different color,and add legend

Upvotes: 2

Views: 6852

Answers (1)

lukeA
lukeA

Reputation: 54247

Melt the data frame from wide to long format, then map the variable name to line color within the aesthetics mappings:

ggplot(melt_roc(test, "D", c("M1", "M2")), 
       aes(d = D, m = M, color = name)) + 
    geom_roc() + 
    style_roc()

enter image description here


You could also do it like this, if you want:

ggplot() + 
  geom_roc(aes(d = D, m = M1, color="roc1"), test) + 
  geom_roc(aes(d = D, m = M2, color="roc2"), test) + 
  scale_color_manual(values=c("roc1"="red", "roc2"="blue"), 
                     name="color legend", guide="legend") + 
  style_roc()

Upvotes: 7

Related Questions