我的目标是绘制具有对数刻度的大型数据集,但不断收到以下错误:
Error in seq.default(min, max, by = by) : 'from' must be a finite number
我尝试了以下一些方法,但仍然收到相同的错误:
- 将相关值转换为数值 ( https://stackoverflow.com/a/34710162/7681828 )
- 向所有值添加一个小值(即 1e-8)以避免无穷大 ( https://groups.google.com/forum/#!topic/ggplot2/7wjkA60cWb )
我的代码/工作如下:
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))
有趣的是,据我了解,默认的 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/