Ошибка «NA не разрешены в подписанных назначениях» при использовании Squash_axis в ggplot2, с набором данных без NA-значений - PullRequest
2 голосов
/ 03 апреля 2020

Я хочу пропустить часть моей оси y для набора данных с большинством значений от -10 до 100, а затем снова с несколькими при 400. Поэтому я хочу сжать эту пустую область. Я уже использую сетку фасетов на своем графике для 3 различных сценариев, поэтому я бы предпочел просто "squa sh" по оси Y и не создавать многократные графики.

Я нашел функцию "squash_axis" на RPubs (https://rpubs.com/huanfaChen/squash_remove_y_axix_ggplot_), что может помочь мне. Но я не могу заставить его работать с моим собственным набором данных, и даже с примером набора данных.

Пример набора данных (мой выглядит довольно похоже, за исключением того, что есть еще один столбец со временем)

dat <- data.frame(group=rep(c('A', 'B', 'C', 'D'), each = 10), 
                 value=c(rnorm(10), rnorm(10)+100)
                 )

Тогда функция оси Squa sh:

require(ggplot2)
squash_axis <- function(from, to, factor) { 
    # A transformation function that squashes the range of [from, to] by factor on a given axis 

    # Args:
    #   from: left end of the axis
    #   to: right end of the axis
    #   factor: the compression factor of the range [from, to]
    #
    # Returns:
    #   A transformation called "squash_axis", which is capsulated by trans_new() function

  trans <- function(x) {    
      # get indices for the relevant regions
      isq <- x > from & x < to
      ito <- x >= to

      # 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("squash_axis", trans, inv))
}

И график из примера:

ggplot(dat,aes(x=group,y=value))+
  geom_point()+
  scale_y_continuous(trans = squash_axis(5, 95, 10))

Затем я получаю ошибку: Ошибка в x [isq] <- from + (x [isq] - from) * фактор: NA не разрешены в подписанных назначениях </p>

Я не понимаю, потому что нет никаких NA в моих данных, а также в данных примера.

Что происходит?

1 Ответ

0 голосов
/ 03 апреля 2020

Использование browser(), если выяснилось, что проблема возникает в части inv преобразования squi sh. Но я мог только догадываться, в чем причина, вероятно, имеет отношение к тому, как устанавливаются разрывы (??). Однако вместо применения преобразования внутри scale_y_continuous я попытался применить его через coord_trans ... et voila, сработало:

library(ggplot2)

dat <- data.frame(group=rep(c('A', 'B', 'C', 'D'), each = 10), 
                  value=c(rnorm(10), rnorm(10)+100)
)

squash_axis <- function(from, to, factor) { 
  # A transformation function that squashes the range of [from, to] by factor on a given axis 

  # Args:
  #   from: left end of the axis
  #   to: right end of the axis
  #   factor: the compression factor of the range [from, to]
  #
  # Returns:
  #   A transformation called "squash_axis", which is capsulated by trans_new() function

  trans <- function(x) {    
    # get indices for the relevant regions
    isq <- x > from & x < to
    ito <- x >= to

    # 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(scales::trans_new("squash_axis", trans, inv, domain = c(from, to)))
}

ggplot(dat,aes(x=group, y = value))+
  geom_point()+
  coord_trans(y = squash_axis(5, 95, 10))

Создано в 2020-04-03 пакетом представ (v0.3.0)

...