【问题标题】:Define new scales axis tranform for ggplot为ggplot定义新的比例轴变换
【发布时间】:2019-04-02 19:41:05
【问题描述】:

我正在尝试使用 scales::trans_new 为 y 轴创建 squared 变换,但遇到了错误。

MWE

data = data.frame(x = 1:10, y = runif(10), z=rnorm(10, 10))

library(ggplot2)
ggplot(data, aes(x, y, size=z)) +
geom_point() +
scale_y_continuous(trans=scales::trans_new("sq", function(x) x^2, function(x) x^(1/2)))

给出错误

if (zero_range(as.numeric(limits))) { :
中的错误 需要 TRUE/FALSE 的缺失值

我尝试添加limitsdomain,但得到了同样的错误。

scale_y_continuous(trans=scales::trans_new("sq", function(x) x^2, function(x) x^(1/2)), limits=c(0,1))
scale_y_continuous(trans=scales::trans_new("sq", function(x) x^2, function(x) x^(1/2), domain=c(0,1)), limits=c(0,1))

这似乎是导致错误的 inverse 参数 - 但 y 的所有值都是正数,所以我不明白。请问我该怎么做?

【问题讨论】:

  • 为什么不能为 y 平方值创建一个新变量并绘制它?
  • @Mike ;因为这需要处理轴缩放/标签——它应该省力;)
  • 最后一个解决方案,然后我会放弃。 scale_y_continuous(trans = scales::trans_new("sq", function(x){x^2}, function(x){sqrt(abs(x))}))
  • 感谢@mike。确实添加abs 有效。 Dave2e 从外观上得出了相同的结论——但我认为有一个更安全的解决方法。再次感谢您的帮助。

标签: r ggplot2


【解决方案1】:

似乎 ggplot 正在使用反函数来设置 y 轴范围和轴标签。如果 y 接近零,则 gglot 正在填充下限并计算负值。这是美化限制的“负面”(双关语)副作用。

这是一个变通方法,修改反函数以防止它接受小于零的值,它将避免负数的平方根错误。
轴的下限总是大于或等于零。

library(ggplot2)

#square function
sq<-function(x){
  x^2
}
#inverse square function (square root)
isq<-function(x){
  print(paste("isq",x))  #debug statement
  x<-ifelse(x<0, 0, x)
  sqrt(x)
}

data =  data.frame(x = 1:10, y = runif(10), z=rnorm(10, 10))

print(data$y)
ggplot(data, aes(x, y, size=z)) +
  geom_point() +
  scale_y_continuous(trans=scales::trans_new("sq", sq, isq))

注意:转生产代码时去掉打印功能。

请参阅下面评论中的链接以获取 Github 上的错误报告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    相关资源
    最近更新 更多