MDK
MDK

Reputation: 300

How to increase the distance of an axis title from the plot when using non-default axis positions?

I'd like to increase the spacing between the facet strips and the axis titles.

I have a plot using facet_grid with axis titles in non-default positions: top and right.

The margin argument of axis.title has no impact at all: theme(axis.title = element_text(margin = margin(20, 20, 20, 20))) does nothing. I've tried suppressing axis.tick and axis.text through scale instead of theme, but it makes no difference.

Here is a reproducible example:

example.data <- data.frame(x.var = rep(-2:2, 5),
                           y.var = rep(-2:2, each=5),
                           boolean.var = as.logical(sample(1:1000, 25) %% 2))

library(ggplot2)
library(tidyr)
example.data %>% ggplot(aes(fill = boolean.var)) +
    geom_rect(xmin = -1, xmax = 1, ymin = -1, ymax = 1) +
    scale_x_continuous(name = "(X Title)", position = "top", limits = c(-0.5,0.5)) +
    scale_y_continuous(name = "(Y Title)", position = "right", limits = c(-0.5,0.5)) +
    scale_fill_discrete(guide = FALSE) +
    facet_grid(y.var ~ x.var) +
    theme(panel.margin=unit(0.25 , "lines"),
          axis.title = element_text(size = 24, margin = margin(20, 20, 20, 20)),
          axis.ticks = element_blank(),
          axis.text = element_blank(),
          axis.title = element_text(margin = margin(20, 20, 20, 20)))

And here is the output:

enter image description here

Upvotes: 1

Views: 3753

Answers (1)

MDK
MDK

Reputation: 300

In this case, you must use the arguments axis.title.x.top and axis.title.y.right.

Individually specifying axis.title.x and axis.title.y, which works when the axis titles are in the default (down, left) positions, still doesn't work.

Here is the full example, with correct spacing:

example.data <- data.frame(x.var = rep(-2:2, 5),
                           y.var = rep(-2:2, each=5),
                           boolean.var = as.logical(sample(1:1000, 25) %% 2))

library(ggplot2)
library(tidyr)
example.data %>% ggplot(aes(fill = boolean.var)) +
    geom_rect(xmin = -1, xmax = 1, ymin = -1, ymax = 1) +
    scale_x_continuous(name = "(X Title)", position = "top", limits = c(-0.5,0.5)) +
    scale_y_continuous(name = "(Y Title)", position = "right", limits = c(-0.5,0.5)) +
    scale_fill_discrete(guide = FALSE) +
    facet_grid(y.var ~ x.var) +
    theme(panel.margin=unit(0.25 , "lines"),
          axis.title = element_text(size = 24, margin = margin(20, 20, 20, 20)),
          axis.ticks = element_blank(),
          axis.text = element_blank(),
          axis.title.x.top = element_text(margin = margin(1, 0, 15, 0)),
          axis.title.y.right = element_text(margin = margin(0, 1, 0, 15)))

Which gives the following output:

enter image description here

Upvotes: 2

Related Questions