Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i specify the width of a ggplot2 colourbar to be half the width of the panel?

Tags:

r

ggplot2

With ggplot2, is there a way to specify a colourbar width which is scaled relative to the size of the plot panel?

i.e. what can be supplied to legend.key.width such that the relative width of the key is kept the same regardless of the size of the plot?

ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  theme(legend.position = "bottom",
        legend.key.width = unit(0.1, "npc")) # not relative

# or could it be done with a custom theme?
my_theme <- function() {
  theme_bw() %+replace%
    theme(legend.position = "bottom", ?)

ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  my_theme()

like image 710
BetaScoo8 Avatar asked Nov 16 '25 19:11

BetaScoo8


1 Answers

You can query the device size and change the legend.key.width accordingly. So your my_theme function could be:

my_theme <- function() {
  theme_bw() +
    theme(legend.position = "bottom", 
          legend.key.width = unit(dev.size()[1] / 10, "inches"))
}

So now when we do:

ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  my_theme()

We get:

enter image description here

But if we narrow the plot down and call the above code again we get

enter image description here

Or if we make it very wide and call it again we get:

enter image description here

like image 172
Allan Cameron Avatar answered Nov 18 '25 09:11

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!