Make legend height same as panel height

Using 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:


r <- rast(ncol = 10, nrow = 10, vals = 1:100)


bob <- 
    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)) +
    legend.margin = margin(0, 0, 0, 0),
    legend.title = element_text(angle = 270)
  ) +
  guides(fill = guide_colorbar(title.position = "right",
                               title.hjust = 0.5))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.