hejseb
hejseb

Reputation: 2164

ggplot theme: grid lines only with facets

I'm trying to create a custom go-to theme for common plots that I make. In these plots, I would like to have grid lines included only when the plot is facetted.

As an example, I am after writing some theme function theme_my() such that if I write:

library(ggplot2)
theme_set(theme_my())
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)

ggplot(mpg, aes(displ, hwy)) +
  geom_point()

The result is the same as

library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

Essentially, what I'm wondering if it is possible to include something into my theme function so that the final +theme(panel.grid.major ...) call is used by the template if the plot is facetted. Is this possible? Or are there other better approaches even?

Upvotes: 0

Views: 1813

Answers (1)

Mark Peterson
Mark Peterson

Reputation: 9560

I am not sure about automating this in to a theme, but one workaround I have leaned on is to save a set of theme designations that I want to use for all of my facet plots, and then just add it to the plot call. I tend to use it for panel.border, but the idea should work the same for you.

First, set a theme without gridlines:

theme_set(theme_minimal() +
            theme(panel.grid.major = element_blank(),
                  panel.grid.minor = element_blank())
          )

Which will give plots like:

ggplot(mpg, aes(displ, hwy)) +
  geom_point()

enter image description here

Next, save the group of theme options that you want to set for your facet plots:

facetSettings <-
  theme(panel.grid.major = element_line("lightgray",0.5),
        panel.grid.minor = element_line("lightgray",0.25))

And then use it:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class) +
  facetSettings

enter image description here

This is not quite as convenient as having it built directly into the theme, but it does have some advantages. If you ever want to use the theme with gridlines outside of a facet, you can (e.g., if building your own multi-panel with cowplot). If you decide that in one instance you actually don't want the special facet settings, you can exclude them. Finally, if it is possible to do this in an actual theme, it will almost certaily be more code than what it takes here.

(That said, if anyone has a way to do it, I am definitely interested and sure that I will find a way to utilize it.)

Upvotes: 1

Related Questions