tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.39k stars 2k forks source link

Themes accept header font family #5887

Open teunbrand opened 1 month ago

teunbrand commented 1 month ago

This PR aims to fix #5886.

Briefly, all themes gain a header_family argument that defaults to base_family. In addition, plot.subtitle and plot.caption no longer inherit from title but the root text element to follow https://github.com/tidyverse/ggplot2/issues/5886#issuecomment-2102552944.

A demonstration:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = class)) +
  labs(
    title = "Fuel efficiency",
    subtitle = "Described for 234 cars from 1999 and 2008.",
    caption = "Source: U.S. Environmental Protection Agency",
    tag = "A"
  ) +
  theme_gray(header_family = "Impact")

Created on 2024-05-10 with reprex v2.1.0

thomasp85 commented 1 month ago

I kind of understand why you want to change the inheritance of subtitle and caption but I'm afraid it would throw users off (especially for subtitle). I now regret we didn't name it "description" or something like that

teunbrand commented 1 month ago

So should we revert the change in inheritance and manually set the header font to the relevant elements in theme_*() functions?

thomasp85 commented 1 month ago

I'm not sure, but I think it would be best at least for subtitle. I'm fine with caption not inheriting from title, I think that was a wrong choice from the start

teunbrand commented 1 month ago

After some thought, I think it would be best to have the header_family = NULL be the default. That way, you don't bake in header_family = "", which is convenient when you're looking to globally change the text font.

Example with the current PR, notice the titles remaining sans serif:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = class)) +
  labs(
    title = "Fuel efficiency",
    subtitle = "Described for 234 cars from 1999 and 2008.",
    caption = "Source: U.S. Environmental Protection Agency",
    tag = "A"
  ) +
  theme_gray()

p + theme_gray() + 
  theme(text = element_text(family = "Times New Roman"))

However, this all resolves nicely when the header font is NULL, notice the all serif text:

p + theme_gray(header_family = NULL) +
  theme(text = element_text(family = "Times New Roman"))

Created on 2024-05-21 with reprex v2.1.0