我想在使用randomForest,partial和plotPartial之后为3个(多)部分依赖图创建一个通用图例。每当我尝试任何建议的解决方案时,它都会带来:
Error in UseMethod("ggplot_build") :
no applicable method for 'ggplot_build' applied to an object of class "trellis"
这是我的代码的示例:
data(boston, package = "pdp") # load the (corrected) Boston housing data
library(pdp)
library(randomForest) # for randomForest, partialPlot, and varImpPlot functions
set.seed(101) # for reproducibility
boston.rf <- randomForest(cmedv ~ ., data = boston, importance = TRUE)
varImpPlot(boston.rf)
# Compute partial dependence data for lstat and rm
pd <- partial(boston.rf, pred.var = c("lstat", "rm"))
# Default PDP
a <- plotPartial(pd)
# Compute partial dependence data for lstat and dis
pd2 <- partial(boston.rf, pred.var = c("lstat", "dis"))
# Default PDP
b <- plotPartial(pd2)
# Compute partial dependence data for rm and dis
pd3 <- partial(boston.rf, pred.var = c("rm", "dis"))
# Default PDP
c <- plotPartial(pd3)
grid_arrange_shared_legend(a,b,c, ncol = 3, nrow = 1)
您最有可能提取的代码用于ggplot2
。plotPartial
使用点阵。
class(a)
[1] "trellis"
从理论上讲,您可以使用合并图例和普通图例latticeExtra
,但是此函数假定图例是相同的:
library(latticeExtra)
library(pdp)
c(a,b)
但我认为色标一开始并不相同,因此以普通图例作图是错误的
grid.arrange(a, b, ncol = 2)
为了使其正常工作,您必须找到一种方法使两个图的图例首先相等。也许尝试这样的事情:
library(patchwork)
# get the range of values
col_limits = range(c(pd$yhat,pd2$yhat,pd3$yhat))
col_limits = c(floor(col_limits[1]),ceiling(col_limits[2]))
plts = lapply(list(pd,pd2,pd3),function(i){
g = ggplot(i,aes(x=!!sym(colnames(i)[1]),
y=!!sym(colnames(i)[2]),fill=yhat)) +
geom_tile() +
scale_fill_viridis_c(limits=col_limits)+
theme_bw()
return(g)
})
combined = plts[[1]] + plts[[2]] + plts[[3]] & theme(legend.position = "bottom")
combined + plot_layout(guides = "collect")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句