Daniel Zhang
Daniel Zhang

Reputation: 53

Adjusting y axis limits in ggplot2 with facet and "free" scales

Here is the plot I can make:

data <- data.frame(Patient = rep(seq(1, 5, 1), 2),
                   Treatment = c(rep("Pre", 5), rep("Post", 5)),
                   Gene.1 = c(rnorm(5, 10, 5), rnorm(5, 50, 5)),
                   Gene.2 = c(rnorm(5,10,5), rnorm(5, 10, 5)))

data %>%
  gather(Gene, Levels, -Patient, -Treatment) %>%
  mutate(Treatment = factor(Treatment, levels = c("Pre", "Post"))) %>%
  mutate(Patient = as.factor(Patient)) %>%
  ggplot(aes(x = Treatment, y = Levels, color = Patient, group = Patient)) +
  geom_point() +
  geom_line() +
  facet_wrap(. ~ Gene, scales = "free") +
  theme_bw() +
  theme(panel.grid = element_blank())

Example plot

The "free" scales function is wonderful, however, I would like to make these two specifications/adjustments:

  1. Y axis begins at 0

  2. Increase the upper y limit by ~10% so that I have some space to add some annotations later on (p-values, etc.) in photoshop.

An alternative strategy might be to make the individual plots and assemble them together, though, this gets a little tedious with many facet elements.

Upvotes: 5

Views: 3310

Answers (1)

r2evans
r2evans

Reputation: 160447

First, reproducibility with random data needs a seed. I started using set.seed(42), but that generated negative values which caused completely unrelated warnings. Being a little lazy, I changed the seed to set.seed(2021), finding all positives.

For #1, we can add limits=, where the help for ?scale_y_continuous says that

  limits: One of:

            • 'NULL' to use the default scale range

            • A numeric vector of length two providing limits of the
              scale. Use 'NA' to refer to the existing minimum or
              maximum

            • A function that accepts the existing (automatic) limits
              and returns new limits Note that setting limits on
              positional scales will *remove* data outside of the
              limits. If the purpose is to zoom, use the limit argument
              in the coordinate system (see 'coord_cartesian()').

so we'll use c(0, NA).

For Q2, we'll add expand=, documented in the same place.

data %>%
  gather(Gene, Levels, -Patient, -Treatment) %>%
  mutate(Treatment = factor(Treatment, levels = c("Pre", "Post"))) %>%
  mutate(Patient = as.factor(Patient)) %>%
  ggplot(aes(x = Treatment, y = Levels, color = Patient, group = Patient)) +
  geom_point() +
  geom_line() +
  facet_wrap(. ~ Gene, scales = "free") +
  theme_bw() +
  theme(panel.grid = element_blank()) +
  scale_y_continuous(limits = c(0, NA), expand = expansion(mult = c(0, 0.1)))

enter image description here

Upvotes: 6

Related Questions