heightDetails 不适用于单位总和

heightDetails does not work with sum of units

我试图用 heightDetails() 找出 ggplot 图例的高度,但出现错误

Error in UseMethod("absolute.units") : no applicable method for 'absolute.units' applied to an object of class "unit"

示例:对于提取,我使用了 g_legend 建议的函数 here:

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

所以假设我们有一个简单的条形图

testplot <- ggplot(mtcars, aes(x=as.factor(gear), fill=as.factor(gear))) + geom_bar()

,我用

testlegend <- g_legend(testplot)

获取图例。 is.grob(testlegend) 表明它确实是一个 grob,而 grid.draw(testlegend) 工作得很好。但是 heightDetails(testlegend) 给了我上面提到的异常。

我的猜测是testlegend$heights包含一个单位之和,heightDetails无法处理。是这个原因吗?如果没有,为什么它不起作用?检索图例高度的替代方法是什么?

我相信您使用的是旧版本 grid/R/gtable;更新应该修复错误。话虽这么说,但没有人知道为什么 absolute.units 在这里使用,根据我的经验,它给出了一个不准确的答案。您可能会发现对 gtable 高度求和比调用其 heightDetails 方法更可靠。