gpt4 book ai didi

r - 缩放geom_密度以将geom_bar与y上的百分比相匹配

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

因为我对数学感到困惑last time I tried asking this ,这是另一个尝试。我想将直方图与平滑分布拟合结合起来。我希望 y 轴以百分比表示。

我找不到获得此结果的方法。上次,我设法找到一种方法将 geom_bar 缩放到与 geom_密度 相同的比例,但这与我想要的相反。

我当前的代码产生以下输出:

ggplot2::ggplot(iris, aes(Sepal.Length)) +
geom_bar(stat="bin", aes(y=..density..)) +
geom_density()

enter image description here

密度和条 y 值匹配,但缩放是无意义的。我想要 y 轴上的百分比,而不是密度。

一些新的尝试。我们首先修改条形图以显示百分比而不是计数:

gg = ggplot2::ggplot(iris, aes(Sepal.Length)) +
geom_bar(aes(y = ..count../sum(..count..))) +
scale_y_continuous(name = "%", labels=scales::percent)

enter image description here

然后我们尝试添加一个 geom_密度 并以某种方式让它正确缩放:

gg + geom_density()

enter image description here

gg + geom_density(aes(y=..count..))

enter image description here

gg + geom_density(aes(y=..scaled..))

enter image description here

gg + geom_density(aes(y=..density..))

与第一个相同。

gg + geom_density(aes(y = ..count../sum(..count..)))

enter image description here

gg + geom_density(aes(y = ..count../n))

enter image description here

似乎偏离了大约 10 倍......

gg + geom_density(aes(y = ..count../n/10))

与:

相同
gg + geom_density(aes(y = ..density../10))

enter image description here

但是临时插入数字似乎是个坏主意。

一个有用的技巧是检查绘图的计算值。如果保存对象,它们通常不会保存在对象中。但是,可以使用:

gg_data = ggplot_build(gg + geom_density())
gg_data$data[[2]] %>% View

由于我们知道 x=6 周围的密度拟合应该约为 0.04 (4%),因此我们可以四处寻找 ggplot2 计算的值来实现这一目标,而我看到的唯一结果是密度/10。

如何使 geom_密度 适合缩放到与修改后的 geom_bar 相同的 y 轴?

额外问题:为什么条形的分组不同?当前函数的小节之间没有空格。

最佳答案

这是一个简单的解决方案:

library(scales) # ! important
library(ggplot2)
ggplot(iris, aes(Sepal.Length)) +
stat_bin(aes(y=..density..), breaks = seq(min(iris$Sepal.Length), max(iris$Sepal.Length), by = .1), color="white") +
geom_line(stat="density", size = 1) +
scale_y_continuous(labels = percent, name = "percent") +
theme_classic()

输出:

enter image description here

关于r - 缩放geom_密度以将geom_bar与y上的百分比相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907260/

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