ggplot2 轴标签点未按指定显示

ggplot2 axis label points not displaying as specified

绘制此数据时,x 和 y 标签默认标签点有多个小数位,例如0.02999999999999999989 而不是像 0.03 这样的合理点。

我试过使用 scale_y_continuous() 函数指定限制和中断等。

ggplot(data, aes(x, y, col = z)) + 
    geom_point(size = 2) + 
    scale_y_continuous(limits = c(-0.03, 0.03), breaks = seq(-0.03, 0.03, 0.01))

我可以通过 breaks = seq() 来改变标签点的位置。在上述代码的情况下,我希望 y 轴从 -0.03 变为 0.03,每 0.01 个标签点。然而,它们仍然没有完全按照指定的方式绘制,并且显示的值与默认绘图中的小数位一样多。例如我希望标签为 0.01 但得到 0.0100000000000000019

编辑:当运行 M. Viking 的代码绘制虹膜数据集时,错误被复制。

如果没有您的数据,我假设您已经在系统中的某处设置了 options(),例如:options(digits = 19),尽管您可能没有明确地这样做。要解决此问题,您可以更改默认值 options() 或仅在 ggplot 之前指定 options()

要重现此问题:

options(digits = 19) 

library(tidyverse)
x <- seq(from = -.03, to = 0.03, 0.001) 
y <- (1.01*x) 
z <- y>0
data <- data.frame(y, x,z)

ggplot(data, aes(x, y, col = z)) + 
  geom_point(size = 2) + 
  scale_y_continuous(
    limits = c(-0.03, 0.03), breaks = seq(-0.03, 0.03, 0.01))

解决上述问题:

options(digits = 5) 
ggplot(data, aes(x, y, col = z)) + 
  geom_point(size = 2) + 
  scale_y_continuous(
    limits = c(-0.03, 0.03), breaks = seq(-0.03, 0.03, 0.01))