Search code examples
rggplot2splitaxisggbreak

How to keep the axis configuration on a plot made with ggplot with split axes using ggbreak?


When I split the x-axis using ggbreak, the plot is displayed correctly. However, if I specify the scale of the y-axis, the y-axis is not displayed as it would be without the specification. How can I solve this?

library(ggplot2)
library(ggbreak)

DF <- data.frame(x = 1:40,
                 y = c(rnorm(n = 10,
                             mean = 1000,
                             sd = 250),
                       rnorm(n = 10,
                             mean = 200,
                             sd = 10),
                       rnorm(n = 10,
                             mean = 1000,
                             sd = 250),
                       rnorm(n = 10,
                             mean = 200,
                             sd = 10)))

# Without log axis

ggplot(data = DF,
       aes(x = x,
           y = y)) +
  geom_point() +
  scale_x_break(breaks = c(10, 20),
                scales = "free")

enter image description here

Note that here the y-axis is printed twice, unlike as desired.

# With log axis

ggplot(data = DF,
       aes(x = x,
           y = y)) +
  geom_point() +
  scale_y_log10(name = "y-axis",
                limits = c(0.1, 10000),
                breaks = c(0.1, 1, 10, 100, 1000, 10000),
                labels = c(expression(10^-1),
                           expression(10^0),
                           expression(10^1),
                           expression(10^2),
                           expression(10^3),
                           expression(10^4))) +
  scale_x_break(breaks = c(10, 20),
                scales = "free")

enter image description here


Solution

  • While this looks like a bug to me, a workaround would be to explicitly specify a duplicated axis for which you remove the breaks, labels and the name:

    library(ggplot2)
    library(ggbreak)
    
    set.seed(123)
    
    ggplot(
      data = DF,
      aes(
        x = x,
        y = y
      )
    ) +
      geom_point() +
      scale_y_log10(
        name = "y-axis",
        limits = c(0.1, 10000),
        breaks = c(0.1, 1, 10, 100, 1000, 10000),
        labels = c(
          expression(10^-1),
          expression(10^0),
          expression(10^1),
          expression(10^2),
          expression(10^3),
          expression(10^4)
        ),
        sec.axis = dup_axis(breaks = NULL, labels = NULL, name = NULL)
      ) +
      scale_x_break(breaks = c(10, 20), scales = "free")
    

    enter image description here