Home > Software design >  ggplot theme(): why doesn't changing line color do anything?
ggplot theme(): why doesn't changing line color do anything?

Time:08-16

I think I must be misunderstanding something about the line = argument in theme(). According to the documentation in ?theme, line = is supposed to affect all line elements in the plot. However, changing the color doesn't do anything, while changing size does work.

library(ggplot2)
ggplot(iris, aes(x = Sepal.Width, Petal.Length))  
  geom_point()  
  geom_smooth()  
  theme(line = element_line(color = "green", size = 5))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2022-08-15 by the reprex package (v2.0.1)

My question is twofold:

  1. Why doesn't changing the color affect any of the lines in the plot?

  2. Why doesn't changing the size affect the line element from geom_smooth()?

EDIT: see @Gregor Thomas's answer for the answer to part 2.

CodePudding user response:

The elements do inherit as advertised, however, they might have parents in between child panel.grid.major.x and grandparent line. This is for example the case for the theme_gray(), which is the default. To test this, you can manually set all theme elements with 'empty' elements. Like so:

library(ggplot2)

my_theme <- theme_get() # Default theme gray
my_theme[] <- lapply(my_theme, function(elem) {
  switch(
    class(elem)[[1]],
    "element_text" = element_text(),
    "element_line" = element_line(),
    "element_rect" = element_rect(),
    elem
  )
})

So with all steps between child and grandparent eliminated, all inherits as it should.

ggplot(iris, aes(Sepal.Width, Sepal.Length))  
  geom_point()  
  my_theme  
  theme(
    line = element_line(colour = "green"),
    axis.line = element_line() # was `element_blank()` by default
  )

Created on 2022-08-15 by the reprex package (v2.0.1)

CodePudding user response:

In ggplot, theme is the way to customize non-data parts of a plot. This is why theme() has no effect on your geom_smooth, geoms are based on data. From the ?theme help page:

Themes are a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends.

If you want to change a data component of the plot, put the customization directly in the layer you want to modify:

geom_smooth(color = "green", size = 5)

As for why your theme(line = element_line(color = "green", size = 5)) doesn't change the color of any lines in the plot, it sets a default color for lines, which can be overriden. It seems like the default theme_grey() overrides the default line color for every type of specific line (major and minor panel grid lines which are the axis lines, axis tick lines, etc.), though some of the sizes must use the default or are set relative to the default, which is why the panel grid lines get huge with your size = 5.

  • Related