R 错误没有适用于'的方法;ggplot#u build';适用于“类”的对象;“格架”;

R 错误没有适用于'的方法;ggplot#u build';适用于“类”的对象;“格架”;,r,random-forest,R,Random Forest,在使用randomForest、partial和plotPartial之后,我想为3个(多)部分依赖图创建一个通用图例。每当我尝试任何建议的解决方案时,它都会想到: Error in UseMethod("ggplot_build") : no applicable method for 'ggplot_build' applied to an object of class "trellis" 下面是我的代码示例: data(boston, pa

在使用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)
data(boston,package=“pdp”)#加载(更正的)boston住房数据
图书馆(pdp)
库(randomForest)#用于randomForest、partialPlot和VarimPlot函数
设定种子(101)#用于再现性

boston.rf您提取的代码很可能是针对
ggplot2
<代码>绘图部分
使用

例如,从理论上讲,您可以使用
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")


你能分享你正在使用的库吗?@Edo上面显示的是randomForest和pdp谢谢,这太棒了!使用plotPartial,我可以更改轴的名称。是否有办法将其添加到每个绘图y/x轴的函数中?以及更改图例上的yhat标签@愚蠢的沃尔夫看到了。使用
+实验室(..)
进行x/y标签和
比例填充绿色(名称=,限值=颜色限值)
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")