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.