3

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))

Graph with axes at 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.

NickCHK
  • 1,093
  • 7
  • 17
  • I don't think there's a very straightforward answer to your seemingly straightforward question. The plot axes are hard-coded in without the ability to "shift" very easily. [Check this related question](https://stackoverflow.com/questions/17753101/center-x-and-y-axis-with-ggplot2) that provides one way to answer. – chemdork123 Apr 23 '20 at 20:00
  • 1
    So probably can't be done in the theme exactly, but it seems straightforward to create a theme-like object with the geom_vline and geom_hline in it. Makes sense. Thank you! – NickCHK Apr 23 '20 at 20:54
  • 1
    Yes, but you'll find that you can't just store them in an object. You have to store them in a list. So: `my_theme <- geom_vline() + geom_hline()` will not work (try it - you get an error), but `my_theme <- list( geom_vline(), geom_hline() )` works. Then to add that to a plot you can use: `ggplot(...) + my_theme` – chemdork123 Apr 23 '20 at 21:04

0 Answers0