0

I am making a plot divided into facets, one for each group. The X-axis is the same for all, but the Y-axis has distant values between each group, so I would like to define limits and breaks for each facet. I have made some attempts by creating functions for both the limits and the breaks, but the problem is here. When I define within scale_y_continuous() the limits as limits= limits_y, the plot appears almost as I expect; but when I add the breaks with breaks = breaks_y, the breaks are changed and do not follow the expected behavior.

Could someone please help me solve this question?

My data frame is as follows:

Group <- c("A", "B", "C")
X <- 1

DF <- expand.grid(X = X,
                  Group = Group)

DF$Y <- c(500, 12000, 30000)
  • For the plot I want a facet for each group, A, B and C.
  • The limits I want for each group are:
    • Group A: c(0, 800)
    • Group B: c(0, 16000)
    • Group C: c(0, 35000)

So I created a logical function for the Y-axis limits and the resulting plot is as expected.

library(ggplot2)

# Function for the limits

limits_y <- function(y) {
  if(max(y) < 1000) {c(0,800)}
  else(if(max(y) > 17000) {c(0,35000)}
       else{c(0,16000)})
}

## Testing the function

limits_y(500)#   For group A
limits_y(12000)# For group B
limits_y(25000)# For group C

# Plot

p1 <- ggplot(data = DF,
       aes(x = X,
           y = Y)) +
  geom_point() +
  facet_grid(Group ~ .,
             scales = "free_y") +
  scale_y_continuous(limits = limits_y)

p1

> limits_y(500)#   For group A
[1]   0 800
> limits_y(12000)# For group B
[1]     0 16000
> limits_y(25000)# For group C
[1]     0 35000

enter image description here

Now for the breaks I want:

  • Group A: seq(0, 800, 400)
  • Group B: seq(0, 16000, 4000)
  • Group C: seq(0, 35000, 7000)

The logical function for the breaks and the resulting plot:

# Function for the breaks

breaks_y <- function(y) {
  if(max(y) < 1000) {seq(0,800,400)}
  else(if(max(y) > 15000) {seq(0,35000,7000)}
       else{seq(0,16000,4000)})
}

## Testing the function

breaks_y(500)#   For group A
breaks_y(12000)# For group B
breaks_y(25000)# For group C

# Plot

p2 <- ggplot(data = DF,
             aes(x = X,
                 y = Y)) +
  geom_point() +
  facet_grid(Group ~ .,
             scales = "free_y") +
  scale_y_continuous(limits = limits_y,
                     breaks = breaks_y)

p2

> breaks_y(500)#   For group A
[1]   0 400 800
> breaks_y(12000)# For group B
[1]     0  4000  8000 12000 16000
> breaks_y(25000)# For group C
[1]     0  7000 14000 21000 28000 35000

Notice that group B has the same breaks as group C, although in the function test, the result is correct.

enter image description here

Daniel Valencia C.
  • 1,749
  • 2
  • 15
  • 32

0 Answers0