Preventing facet_wrap repeating axis labels in each facet when combined with coord_flip

48 Views Asked by At

I want to combine facet_wrap and cord_flip, but when I do I get the axis categories repeated in every facet.

Here's some demo data.

demo_data = data.frame(locus = c(paste0("locus_", rep(1, 5)),
                                 paste0("locus_", rep(2, 5)),
                                 paste0("locus_", rep(3, 5)),
                                 paste0("locus_", rep(4, 5)),
                                 paste0("locus_", rep(5, 5))),
                       sample = rep(paste0("sample_", seq(1:5))),
                       value = sample(100, 25)) %>%
  mutate(ci_upper = value + 10,
         ci_lower = value - 10)

When I plot it, the values on the original x-axis were sample_1 to sample_5. When I flip the coordinates, samples1-5 are repeated in every facet, which makes the plot look too cluttered with text. I want them to appear only in the facets on the left, as would normally happen with facet_wrap.

ggplot(demo_data, aes(x = sample, y = value)) +
  geom_point() +
  geom_errorbar(aes(ymin = ci_lower, 
                    ymax = ci_upper)) +
  facet_wrap(~ locus, scales = "free") +
  coord_flip()

enter image description here

Any ideas how to achieve this?

I've tried searching on here, but can't find anything relevant

1

There are 1 best solutions below

0
MrFlick On BEST ANSWER

This issue is that you have marked both the x and y scales as "free" so they can have different values in each box. If you want a shared axis, you need non-free scales. So change scales="free" to scales="free_x" so only the x-axis is free. Try

ggplot(demo_data, aes(x = sample, y = value)) +
  geom_point() +
  geom_errorbar(aes(ymin = ci_lower, 
                    ymax = ci_upper)) +
  facet_wrap(~ locus, scales = "free_x") + 
  coord_flip()

enter image description here