在使用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)发布于 2020-09-02 19:17:11
您提取的代码很可能是为ggplot2编写的。plotPartial使用lattice。
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")

https://stackoverflow.com/questions/63703829
复制相似问题