Is there a way to change the width and height of the keys in the legend with ggplot2? In the following example, I would like to replace the dots in the legend with rectangles that I could adjust the width and height. I have tried to use keywidth without success.
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
theme(
legend.position = "top",
legend.title = element_blank()
) +
guides(
color = guide_legend(
label.position = "top",
override.aes = list(shape = 15, size = 5),
keywidth = unit(2, "cm") # This is not giving me what I was expecting.
)
)

Created on 2020-07-23 by the reprex package (v0.3.0)
While @Ian's answer works, there's a far simpler way, which is to define the legend key glyph you want to use right in the geom_point() call. The important point to note is that if we specify the key glyph should be a rect, we need to provide the fill aesthetic (or you'll just have empty rectangles for the glyphs):
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point(aes(fill=Species), key_glyph='rect') +
theme(
legend.position = "top",
legend.title = element_blank()
)

You should be able to adjust the key dimensions from there via guides() or theme() changes to suit your needs.
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