0

I am trying to collapse part of the x-axis of a ggplot2 diagram because I have time trends in two periods, but missing data for a few years where it is not reported.

Example Data:

y_val <- 0:250
x_val <- c(1998:2003, 2010:2016)
set.seed(1234)
data <- data.frame(x = sample(x_val, 30, replace = TRUE),
                   y = sample(y_val, 30, replace = TRUE))


p <- ggplot(data, aes(x, y)) + geom_point()
p

It currently looks something like this: enter image description here

I have tried to use the code and instructions from this post in order to shrink the gaps between the years, which used to work:

squish_trans <- function(from, to, factor) {

  trans <- function(x) {

    # get indices for the relevant regions
    isq <- x > from & x < to #observations between the from and to
    ito <- x >= to #observations larger and the same as 2 

    # apply transformation
    x[isq] <- from + (x[isq] - from)/factor 
    x[ito] <- from + (to - from)/factor + (x[ito] - to)

    return(x)
  }

  inv <- function(x) {

    # get indices for the relevant regions
    isq <- x > from & x < from + (to - from)/factor
    ito <- x >= from + (to - from)/factor

    # apply transformation
    x[isq] <- from + (x[isq] - from) * factor
    x[ito] <- to + (x[ito] - (from + (to - from)/factor))

    return(x)
  }

  # return the transformation
  return(trans_new("squished", trans, inv))
}

However, this code no longer works, and throws an error:

Error in x[isq] <- from + (x[isq] - from) * factor : NAs are not allowed in subscripted assignments.

Is there a way to workaround this problem, without having to use facets? I am aware that a broken x axis can be misleading, but in this case it is more distracting to show the missing years because they are years in which data is unavailable and the white space is not analytically useful.

  • Does this answer your question: https://stackoverflow.com/questions/61010786/error-nas-are-not-allowed-in-subscripted-assignments-while-using-squash-axis-i/61012644#61012644 – stefan May 28 '20 at 12:32
  • Oh my god thank you. What a strange error? And this didn't occur to me in the Fall? I feel like there was an update change of some kind. – Andrew Messamore May 28 '20 at 15:12
  • 1
    Does this answer your question? [Error "NAs are not allowed in subscripted assignments" while using Squash\_axis in ggplot2, with dataset without NA-values](https://stackoverflow.com/questions/61010786/error-nas-are-not-allowed-in-subscripted-assignments-while-using-squash-axis-i) – stefan May 29 '20 at 07:36

0 Answers0