Changing the Legend Title in a {ggplot2} geom

R

This came up in class this past week and here we are: In how many ways can I change thee, oh legend title? It doesn’t matter what data we use; the Ikea data from 2020’s TidyTuesday are used here.

Ani Ruhil true
02-06-2021
library(tidyverse)
tidytuesdayR::tt_load('2020-11-03') -> tuesdata 

    Downloading file 1 of 1: `ikea.csv`
tuesdata$ikea -> ikea

Say we have the following bar-chart. But the legend title of other _colors deserves to be improved upon.

ggplot(ikea) +
  geom_bar(
    aes(
      x = forcats::fct_infreq(category),
      fill = other_colors
      ),
    position = "dodge"
    ) +
  coord_flip() +
  theme(legend.position = "bottom") +
  labs(x = "Category", y = "Frequency") -> p1

p1

One way of doing that would be to use the labs() command, as shown below.

p1 +
  labs(fill = "Are Other Colors Available?")

Then we have the scale_fill_discrete() option …

p1 +
  scale_fill_discrete(
    name = "Are Other Colors Available?"
    )

How about the guides() route? Sure thing!

p1 +
  guides(
    fill = guide_legend(
      title = "Are Other Colors Available?"
      )
    )

Could the theme(legend.title = ...) work? Nope, because it seems to inherit from title and there is no easy way I see to specify the desired title inside element_text()

The only other simple way I can think of is to modify the variable name prior to plotting but this would be inefficient; labs() wins unless you are looking to tweak color, size, face, etc of the legend title/labels.

ikea %>%
  rename(
    `Are Other Colors Available?` = other_colors
    ) %>%
  ggplot() +
  geom_bar(
    aes(
      x = forcats::fct_infreq(category),
      fill = `Are Other Colors Available?`
      ),
    position = "dodge"
    ) +
  coord_flip() +
  theme(legend.position = "bottom") +
  labs(x = "Category", y = "Frequency")

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY-SA 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Ruhil (2021, Feb. 6). From an Attican Hollow: Changing the Legend Title in a {ggplot2} geom. Retrieved from https://aniruhil.org/posts/2021-02-06-changing-the-legend-title-in-a-ggplot2-geom/

BibTeX citation

@misc{ruhil2021changing,
  author = {Ruhil, Ani},
  title = {From an Attican Hollow: Changing the Legend Title in a {ggplot2} geom},
  url = {https://aniruhil.org/posts/2021-02-06-changing-the-legend-title-in-a-ggplot2-geom/},
  year = {2021}
}