geom_raster(), I get a legend with a colorbar defining the values of the fill colors. I would like to make this colorbar the same height as the plot panel. This would mimic the look of
terra's raster plots.
The same question was asked a few years ago on SO here: LINK
The proposed solution is hackish in the extreme and requires a deep understanding of the underlying gtable structure. Given the power of
ggplot2, it really seems like there should be a more user-friendly way of doing this. I assume it should involve
guide_colorbar(barheight = SOMETHING), but I can't for the life of me figure out what that SOMETHING is... I mean, I would think just grabbing the height of a panel from the gtable would do it, but those are all set to
unit(1, "npc")! And that just makes zero sense to me. Even more confusing, if you use
gtable_show_layout(), it shows the panel heights as
unit(1, "null"), which is zero height! How could that be?!!!
I'm just really stumped on this one and could use some help...
Here's a reprex:
library(ggplot2) library(terra) library(viridis) r <- rast(ncol = 10, nrow = 10, vals = 1:100) plot(r) bob <- expand.grid( x = 1:10, y = 1:10 ) bob$z <- 1:100 ggplot(bob, aes(x, y, fill = z)) + geom_raster() + scale_fill_viridis(name = "bob's height is confusing", discrete = FALSE) + scale_x_continuous(expand = expansion(0)) + scale_y_continuous(expand = expansion(0)) + theme( legend.margin = margin(0, 0, 0, 0), legend.title = element_text(angle = 270) ) + guides(fill = guide_colorbar(title.position = "right", title.hjust = 0.5))