Setting different axis limits for each facet in gg

2020-02-15 02:42发布

问题:

The general solution that I would like is to be able to specify arbitrary axis limits for each facet independently.

Basic functionality is obtained by setting the scales to be free. For example:

ggplot(diamonds, aes(x = carat, y = price)) + geom_point() + facet_wrap(~clarity, nrow = 4, ncol = 2, scales = "free")

This is actually a really nice feature, but in practice is not always that useful. Often what we want is to have subgroups of variables comparable on the same axis. As a toy example, consider the diamonds case above. We might want to have all facets in column one have the same axis limits and all the facets in column two have the same axis limits (but different from column one).

Is there a solution for accomplishing this with standard ggplot usage.

回答1:

Before this is closed, I think it is important to expand the suggestion by @Axeman : this may not be possible with facet_wrap directly, but the behavior can be achieved by chunking the groups you want and stitching them together with cowplot. Here, I separated into "low" and "high" quality, but the grouping is arbitrary and could be whatever you wanted. Likely want to mess with the style a bit, but the default from cowplot is acceptable for this purpose:

library(cowplot)

lowQ <- 
  ggplot(diamonds %>%
           filter(as.numeric(clarity) <= 4)
         , aes(x = carat
               , y = price)) +
  geom_point() +
  facet_wrap(~clarity
             , nrow = 1)  


hiQ <- 
  ggplot(diamonds %>%
           filter(as.numeric(clarity) > 4)
         , aes(x = carat
               , y = price)) +
  geom_point() +
  facet_wrap(~clarity
             , nrow = 1)

plot_grid(lowQ, hiQ, nrow = 2)



标签: r ggplot2