Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify ggplot2 legend keys?

Tags:

r

legend

ggplot2

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)

like image 380
Philippe Massicotte Avatar asked Oct 27 '25 07:10

Philippe Massicotte


1 Answers

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

enter image description here

You should be able to adjust the key dimensions from there via guides() or theme() changes to suit your needs.

like image 150
chemdork123 Avatar answered Oct 28 '25 21:10

chemdork123