can i convert a base plot in r to a ggplot object?

人走茶凉 提交于 2020-02-03 23:42:12

问题


I'm somewhat new to R and I love ggplot - that's all I use for plotting, so I don't know all the archaic syntax needed for base plots in R (and I'd rather not have learn it). I'm running pROC::roc and I would like to plot the output in ggplot (so I can fine tune how it looks). I can immediately get a plot as follows:

size <- 100
response <- sample(c(0,1), replace=TRUE, size=size)
predictor <- rnorm(100)
rocobject <- pROC::roc(response, predictor,smooth=T)
plot(rocobject)

To use ggplot instead, I can create a data frame from the output and then use ggplot (this is NOT my question). What I want to know is if I can somehow 'convert' the plot made in the code above into ggplot automatically so that I can then do what I want in ggplot? I've searched all over and I can't seem to find the answer to this 'basic' question. Thanks!!


回答1:


No, I think unfortunately this is not possible.

Even though this does not answer your real question, building it with ggplot is actually not difficult.

Your original plot:

plot(rocobject)

In ggplot:

library(ggplot2)
df<-data.frame(y=unlist(rocobject[1]), x=unlist(rocobject[2]))
ggplot(df, aes(x, y)) + geom_line() + scale_x_reverse() + geom_abline(intercept=1, slope=1, linetype="dashed") + xlab("Specificity") + ylab("sensitivity")




回答2:


Better late than never? I think the ggplotify package might do what you want. You basically plug in your plot generating code to the as.ggplot() function like so:

p6 <- as.ggplot(~plot(iris$Sepal.Length, iris$Sepal.Width, col=color, pch=15))

https://cran.r-project.org/web/packages/ggplotify/vignettes/ggplotify.html



来源:https://stackoverflow.com/questions/38011885/can-i-convert-a-base-plot-in-r-to-a-ggplot-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!