gpt4 book ai didi

r - ggplot stat_summary_bin 故障?

转载 作者:行者123 更新时间:2023-12-03 18:18:49 25 4
gpt4 key购买 nike

我很高兴 discover ggplot 具有分箱散点图,这对于探索和可视化大数据中的关系非常有用。然而,顶部垃圾箱似乎行为不端。这是一个示例:所有 bin 平均值都大致线性对齐,正如它们应该的那样,但顶部的平均值在两个维度上都关闭:

enter image description here

编码:

library(ggplot2)

# simulate an example of linear data
set.seed(1)
N <- 10^4
x <- runif(N)
y <- x + rnorm(N)
dt <- data.frame(x=x, y=y)

ggplot(dt, aes(x, y)) +
geom_point(alpha = 0.1, size = 0.01) +
stat_summary_bin(fun.y='mean', bins=10, color='orange', size=5, geom='point')

有没有简单的解决方法(应该在哪里发布)?

最佳答案

stat_summary_bin实际上是从 bin 中排除了具有最大 x 值的两行,而这两个值的结尾是 bin = NA .这两个排除值的平均值绘制为常规 bin 右侧的单独 bin。首先,我展示了原始图中出了什么问题,然后我提供了一种解决方法来获得所需的行为。

原剧情出了什么问题

要查看原始绘图中出了什么问题,请创建一个带有两次调用 stat_summary_bin 的绘图。我们计算每个 bin 的平均值和每个 bin 中的值的数量。然后使用 ggplot_build捕获 ggplot 为创建绘图而生成的所有内部数据。

p1 = ggplot(dt, aes(x, y)) + 
geom_point(alpha = 0.1, size = 0.01) +
stat_summary_bin(fun.y=mean, bins=10, size=5, geom='text',
aes(label=..y..)) +
stat_summary_bin(fun.y=length, bins=10, size=5, geom='text',
aes(label=..y.., y=0))

p1b = ggplot_build(p1)

现在让我们看看 mean 的数据和 length层,分别。为简洁起见,我只打印了 bin 9 到 11(最右边的三个 bin)。 Bin 11 是“额外的”bin,你可以看到它只包含两个值(它的 label 是下面第二个表中的 2),并且这两个值的平均值是 -0.1309998 ,如下面的第一个表格所示。
p1b$data[[2]][9:11,c(1,2,4,6,7)]

        label bin          y         x      width
9 0.8158320 9 0.8158320 0.8498505 0.09998242
10 0.9235531 10 0.9235531 0.9498329 0.09998242
11 -0.1309998 11 -0.1309998 1.0498154 0.09998244

p1b$data[[3]][9:11,c(1,2,4,6,7)]

   label bin    y         x      width
9 1025 9 1025 0.8498505 0.09998242
10 1042 10 1042 0.9498329 0.09998242
11 2 11 2 1.0498154 0.09998244


那两个值是哪两个?看起来它们来自原始数据框中 x 值最高的两行:
mean(dt[order(-dt$x), "y"][1:2]) 

[1] -0.1309998


我不确定如何 stat_summary_bin正在设法对数据进行分箱,以便排除两个最高的 x 值。

获得所需行为的解决方法

一种解决方法是自己汇总数据,这样您就可以完全控制数据箱的创建方式。下面的示例使用您的原始代码,然后以蓝色绘制预先汇总的值,以便您可以比较行为。我已经包含了 dplyr包,以便我可以使用链接运算符 ( %>% ) 来动态汇总数据:
library(dplyr)

ggplot(dt, aes(x, y)) +
geom_point(alpha = 0.1, size = 0.01) +
stat_summary_bin(fun.y='mean', bins=10, color='orange', size=5, geom='point') +
geom_point(data=dt %>%
group_by(bins=cut(x,breaks=seq(min(x),max(x),length.out=11), include.lowest=TRUE)) %>%
summarise(x=mean(x), y=mean(y)),
aes(x,y), size=3, color="blue") +
theme_bw()

enter image description here

关于r - ggplot stat_summary_bin 故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320710/

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