I am trying to find out the height of the legend of a ggplot with heightDetails(), but I get the error
Error in UseMethod("absolute.units") : no applicable method for 'absolute.units' applied to an object of class "unit"
Example: For the extraction, I used the function g_legend suggested 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)
}
So assume we have a simple barplot
testplot <- ggplot(mtcars, aes(x=as.factor(gear), fill=as.factor(gear))) + geom_bar()
, I use
testlegend <- g_legend(testplot)
to get the legend. is.grob(testlegend) suggest that it is indeed a grob, and grid.draw(testlegend) works just fine. But heightDetails(testlegend) gives me the above mentioned exception.
My guess is that testlegend$heights includes a sum of units, and heightDetails can't deal with it. Is this the reason? If not, why doesn't it work? And what is an alternative way to retrieve the height of the legend?
I believe you're using an old version of grid/R/gtable; updating should fix the error. That being said, no-one has a clue why absolute.units is used here, and in my experience it gives an inaccurate answer. You may find it more reliable to sum the gtable heights than to call its heightDetails method.