2

Is it possible to specify distinct labels axes in each panel within ggplot?

For example:

ggplot(diamonds, aes(x = carat, y = price)) + geom_point() + facet_grid(~cut)

In this figure we have five panels, I would like to specify my own label for each of them. The default output is to produce one label for all the axes.

Is there a solution that doesn't involve using grid.arrange as is done here:

Modify x-axis labels in each facet

Community
  • 1
  • 1
skleene
  • 389
  • 3
  • 13

1 Answers1

1

(I'm assuming you're referring to axis titles, not labels.)

Out of principle, no. The philosophy behind facets is that they share common aesthetic mappings. But we can trick ggplot to get what we want, for example:

ggplot(diamonds, aes(x = carat, y = price)) + 
  geom_point() + 
  facet_grid(~cut, switch = 'x') +
  theme(axis.title.x = element_blank(),
        strip.background = element_blank())

The trick is to switch the facet strips to the bottom of the plot. Then we turn off the strip background and the original x-axis title to create the appearance of separate axis titles.

enter image description here

(You may also want to change strip.text.x = element_text(size = ??) to the same size as the y-axis title. However, it seems to not be documented what the defualt size is for axis titles.)

Community
  • 1
  • 1
Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Nice solution. I am actually looking to change the labels though. The facets share an aesthetic mapping, but the _interpretation_ of the mapping changes across panels and I want to indicate this with the change in label. – skleene Sep 13 '16 at 19:03
  • The labels in the example are 1 to 5. It's not clear what you'd want with that. – Axeman Sep 13 '16 at 19:08