I am creating an R package that will produce graphs that naturally go into all four quadrants - positive and negative values on the x and y axis.
I would like to create a ggplot2 theme that will center the axes at (0,0)
to help make this look nice!
Obviously I could do this on a graph-by-graph basis by adding geom_vline
and geom_hline
. Effectively, this is what I want the result to look like:
library(ggplot2)
ggplot(mtcars, aes(x = mpg-20, y = hp-150)) +
geom_point() +
theme_void() +
geom_vline(aes(xintercept = 0)) +
geom_hline(aes(yintercept = 0))
This is perfect - add some decoration and I'm done.
However, I would like to do this in the theme so that users of the package can just do +theme_fourquadrant()
and have it done for them.
When I try to define a theme like this...
theme_fourquadrant <- function() {
theme_void() %+replace%
geom_vline(aes(xintercept = 0)) +
geom_hline(aes(yintercept = 0))
}
I get the error that %+replace%
requires a theme object on either side. If I replace that with +
I get that you can't add geoms to a theme object, naturally.
I also haven't had luck trying to only get a major grid axis to show up for 0.
Is this possible to do? I'm a little worried that "0" counts as data and so the theme will refuse to have anything to do with it. I'm sure there are some ways I can do this by not making it happen in the theme, but having it done in the theme would be ideal.