R应用对数尺度时的选择性有限数误差

标签 r ggplot2

我的目标是绘制具有对数刻度的大型数据集,但不断收到以下错误:

Error in seq.default(min, max, by = by) : 'from' must be a finite number

我尝试了以下一些方法,但仍然收到相同的错误:

我的代码/工作如下:

library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.6.2
library(reprex)

# Subset original data with dput
data <- structure(list(
  x = c(500, 525, 500, 525), 
  y = as.numeric(
    c(0.070860012, 0.052973494, 
      6.91685849999998e-310,
      4.68262549999999e-310))), 
  row.names = c(NA, -4L), 
  class = c("tbl_df", "tbl", "data.frame"))

# View data
data
#> # A tibble: 4 x 2
#>       x         y
#>   <dbl>     <dbl>
#> 1   500 7.09e-  2
#> 2   525 5.30e-  2
#> 3   500 6.92e-310
#> 4   525 4.68e-310

# Error when plotting with log scale
ggplot(data, aes(x, y)) +
  geom_line() +
  scale_y_log10()
#> Error in seq.default(min, max, by = by): 'from' must be a finite number

# Check values are finite
is.finite(data$y)
#> [1] TRUE TRUE TRUE TRUE

# Works fine without log scale
ggplot(data, aes(x, y)) +
  geom_line()


# Works fine with no duplicate x
ggplot(data %>% slice(1:2),
       aes(x, y)) +
  geom_line() +
  scale_y_log10()


# Reproducible example may suggest an issue with the y values in data
rep <- data.frame(
  x = sample(c(500, 525, 500, 525)),
  y = runif(4, max = 1e-300))

# Plotting the reprex with log scale doesn't throw an error
ggplot(rep, aes(x, y)) +
  geom_line() +
  scale_y_log10()

reprex package于2020年5月1日创建(v0.3.0)

非常感谢任何有关错误发生原因或替代方法的见解!

最佳答案

问题是您非常接近 R 的指数限制,具体来说,这似乎是一个浮点错误。请参阅以下我与 R 控制台的交流示例:

> 1e-310
[1] 1e-310   # seems ok
> 1e-315
[1] 1e-315   # seems ok
> 1e-320
[1] 9.999889e-321  # hm... seems like floating point error
> 1e-324
[1] 0   # R gives up.

这意味着……不可能绘制一个值在 1e-324 左右的点。然而,1e-310 看起来没问题……那么为什么我们不能绘制它呢? R 或 ggplot 是否以某种方式尝试访问 1e-324 左右的数字?事实上,答案是"is"。

ggplot 始终将绘图区域扩展为超出绘图限制,在本例中将包括 Xe-310 编号的下限。如果是扩展导致了问题,我们应该能够通过删除沿该轴的绘图扩展来解决这个问题,这是有效的:

ggplot(data, aes(x, y)) +
    geom_line() +
    scale_y_log10(expand=c(0.04,0))

enter image description here

有趣的是,据我了解,默认的 expand= 是 0.05。当您将其输入为下扩展时,您会再次收到错误:

ggplot(data, aes(x, y)) +
    geom_line() +
    scale_y_log10(expand=c(0.05,0))

Error in seq.default(min, max, by = by) : 'from' must be a finite number

关于R应用对数尺度时的选择性有限数误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61535394/

相关文章:

r - 如何解决 devtools 不需要的副作用

r - 延长一定长度的运行

r - 由于地理单位不同,我在向 ggmap 添加 shapefile 时遇到问题

r - 如何在ggplot2中跨时间线绘制多行

r - geom_rect 失败 : Error in eval(expr, 环境,enclos):找不到对象 'variable'

r - 为什么我得到 "warning longer object length is not a multiple of shorter object length"?

r - 你能把标签放在单杠之间吗?

r - 如何使用 Textmate 的 R Bundle 加载我的 .RProfile

r - 如何使用 ggplot2 绘制重叠范围

r - 自动确定情节图例的位置