gpt4 book ai didi

r - ggplot2 网格重叠超出边界

转载 作者:行者123 更新时间:2023-12-01 12:09:30 26 4
gpt4 key购买 nike

我在 [0,1] 中统一创建点,每个点都有观察值。但是 ggpolot 显示了一些大于 1 的观测值,这些观测值在边界之外。为什么即使坐标在 0 和 1 范围内也会发生这种情况?你知道如何避免这种情况吗?

x=runif(10^6)
y=runif(10^6)
z=rnorm(10^6)

new.data=data.frame(x,y,z)

library(ggplot2)

ggplot(data=new.data) + stat_summary_2d(fun = mean, aes(x=x, y=y, z=z))

enter image description here

最佳答案

这是一个与用于分箱的网格有关的问题。让我们使用一个更小的例子。

set.seed(42)
x=runif(10^3)
y=runif(10^3)
z=rnorm(10^3)

new.data=data.frame(x,y,z)

library(ggplot2)

(g <- ggplot(data=new.data) +
stat_summary_2d(fun = mean, aes(x=x, y=y, z=z)) +
geom_point(aes(x, y)))

现在让我们放大左上角的那个框

g + coord_cartesian(xlim = c(0.02, 0.075), ylim = c(0.99, 1.035), 
expand = FALSE)

如您所见,该框从 y = 1 以下开始但延伸至该值以上因为您正在根据某些 binwidth 对观察结果进行分箱。如果使用直方图,也会出现同样的现象。

ggplot(data.frame(x = runif(1000, 0, 1)), aes(x)) +
geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

geom_histogram 中,可以通过设置 boundary 参数来避免这种情况为 0,箱数为总长度的倍数。

ggplot(data.frame(x = runif(1000, 0, 1)), aes(x)) +
geom_histogram(boundary = 0, binwidth = 0.1)

因此,您的解决方案是将 binwidth 设置为 1/n,其中 n 是一个整数

ggplot(data=new.data) + 
stat_summary_2d(fun = mean, aes(x=x, y=y, z=z), binwidth = 0.1) +
geom_point(aes(x, y))

reprex package 创建于 2018-11-04 (v0.2.1.9000)

关于r - ggplot2 网格重叠超出边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53143923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com