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()
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:

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

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

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