ggplot2中如何压缩或放大部分轴?

问题描述 投票:0回答:1

我在这个问题之后有一个新问题。我希望压缩Y轴的一部分,放大另一部分。我使用自定义函数

magnify_trans
,但出现错误。功能和例子是:

> magnify_trans <- function(intercept, reducer) {
    trans <- function(x, i = intercept, r = reducer) {
      sapply(x, function(x) {
        if (x > i) x
        else x / r + i
      })
    }
    inv <- function(x, i = intercept, r = reducer) {
      sapply(x, function(x) {
        if(!is.na(x)) {
          if (x > i) x
          else (x - i) * r
        }
      })
    }
    trans_new(name = 'custom',
              transform = trans,
              inverse = inv)
}
>   ggplot(data.frame(x = c(-10, 30), y = c(0, 250)), aes(x, y)) +
+     stat_function(fun = function(x) 12 + 180 / (1 + exp(-.759*(x - 7.69))),
+                   size = 2,
+                   color = "yellow") +
+     coord_cartesian(ylim = c(0, 250))+
+     geom_abline(intercept = 44, slope = 0, lty = 2)+
+     scale_x_continuous(limits = c(-5, 25)) +
+     coord_trans(y = magnify_trans(intercept = 44, reducer = 20))   
Coordinate system already present. Adding new coordinate system, which will replace the existing one.
Error in UseMethod("rescale") : 
  no applicable method for 'rescale' applied to an object of class "list"

magnify_trans
函数定义了一个新的变压器。我尝试使用
trans_exp(10)
等通用转换器来替换示例中的
magnify_trans
函数,效果很好。是不是自定义函数有问题?我的ggplot2版本是3.5.0,R版本是4.3.3。

ggplot2
1个回答
0
投票

我的问题已经被人工智能工具解决了。它将

sapply
函数替换为 R 基函数
ifelse

magnify_trans <- function(intercept, reducer) {
      trans <- function(x, i = intercept, r = reducer) {
        ifelse(x > i, x, x / r + i)
      }
      inv <- function(x, i = intercept, r = reducer) {
        ifelse(!is.na(x), ifelse(x > i, x, (x - i) * r), NA)
      }
      trans_new(name = 'custom',
                transform = trans,
                inverse = inv)
      }
© www.soinside.com 2019 - 2024. All rights reserved.