hadley / ggplot2-book

ggplot2: elegant graphics for data analysis
https://ggplot2-book.org/
1.55k stars 678 forks source link

Theme guidelines for developers of extension packages #171

Open clauswilke opened 4 years ago

clauswilke commented 4 years ago

It would be good to provide some guidelines for developers adding themes to their extension packages. I suggest the following four points. It doesn't have to add a lot of text to the book.

  1. Always define your theme by starting from an existing theme.

  2. Use %+replace%, not +, to modify the starting theme, and set complete = TRUE.

  3. Don't overwrite the default theme.

  4. If your extension package defines new theme elements (new in ggplot 3.3.0), add them to the default theme. As an example of a user-defined new theme element, consider using the code in this comment.

clauswilke commented 4 years ago

I just saw that there is already some existing text on this topic. I may take a stab editing it along the lines of this issue.

clauswilke commented 4 years ago

@thomasp85 Regarding my point 2 above, I suggest something like the following to explain the issue. The main goal for theme developers should be to write themes that behave similarly to the default.

library(ggplot2)

df <- data.frame(x = 1:3, y = 1:3)
base <- ggplot(df, aes(x, y)) + geom_point()

mytheme <- theme_classic() + 
  theme(
    axis.line.x = element_line(color = "red"),
    axis.line.y = element_line(color = "blue")
  )

base + mytheme


# doesn't work, lines are not removed
base + mytheme + theme(axis.line = element_blank())


mytheme2 <- theme_classic() %+replace%
  theme(
    axis.line.x = element_line(color = "red"),
    axis.line.y = element_line(color = "blue"),
    complete = TRUE
  )

# works as before
base + mytheme2


# now also works
base + mytheme2 + theme(axis.line = element_blank())

Created on 2019-12-17 by the reprex package (v0.3.0)