使用 scale_x_log10 时如何在 geom_histogram 中设置 ggplot2 binwidth?

Posted

技术标签:

【中文标题】使用 scale_x_log10 时如何在 geom_histogram 中设置 ggplot2 binwidth?【英文标题】:How do I set ggplot2 binwidth in geom_histogram when using scale_x_log10? 【发布时间】:2021-03-21 06:08:20 【问题描述】:

在使用 scale_x_log10 时在 geom_histogram 中设置 ggplot2 binwidth 会产生奇怪的直方图。

我想在没有找到解决方法here 的情况下调整 binwidth。

我不想使用解决方法的一个原因是我不喜欢它;似乎应该有一个更好的方法内置到 ggplot 中。另一个原因是当我在我的数据集上尝试它时它不起作用。

我正在使用 facet_wrap,因此解决方案需要使用它,但我正在使用的示例代码被精简到最低限度。

当我允许默认 binwidth 时,我得到一个不错的直方图:

library(ggplot2)
data(diamonds)
ggplot(data=diamonds, aes(x=price/carat)) +
  geom_histogram() +
  scale_x_log10()# +
  # facet_wrap(~cut, ncol=1, scales='free_y')

但是,当我设置 binwidth 时,无论 binwidth 是多少,我都会得到一个填充整个图形(或单个 bin?)的均匀分布(除非 binwidth=1,这会产生看起来像两个 bin 或双峰的情况均匀分布?):

ggplot(data=diamonds, aes(x=price/carat)) +
  geom_histogram(binwidth=10) +
  scale_x_log10()# +
  # facet_wrap(~cut, ncol=1, scales='free_y')

设置中断会产生相同的实心方块和新的中断。设置限制清除图表。

在 ggplot() 中设置 binwidth 本身会使图形与默认 binwidths 保持不变,大概是因为 geom_histogram 覆盖了它。而且,scale_x_log10 不接受 binwidth。

在使用 scale_x_continuous 而不是 scale_x_log10 时可以设置 binwidth。

【问题讨论】:

【参考方案1】:

尝试输入总宽度的一小部分,使 binwidth 与 bin 的数量相关,例如 1/(n_bins - 1)

library(ggplot2)

data(diamonds)
ggplot(data=diamonds, aes(x=price/carat)) +
  geom_histogram(binwidth = 1/50) +
  scale_x_log10()

【讨论】:

完美!谢谢! 但是,我想知道为什么会这样。怎么了?它怎么知道我们的意思是设置相对于比例的 binwidth,而不是字面上的 0.02? 而且,为什么不设置恒定的 binwidth,使像素宽度随比例减小? geom_histogramgeom_bar 加上stat_bin 的别名。我认为在这种情况下它使用stat_bin 来解释binwidth 参数。 stat_binbinwidth 的描述:默认为数据范围的 1/30。因此,您正在根据数据范围设置 binwidth。我不确定为什么它似乎没有使用您数据的绝对规模。也许因为它是一个转换的比例,所以它只是将范围默认为 1。不完全确定。

以上是关于使用 scale_x_log10 时如何在 geom_histogram 中设置 ggplot2 binwidth?的主要内容,如果未能解决你的问题,请参考以下文章

如何设置使用 geo.js 查找位置的超时时间?

PHP GEO 位置重定向 - 有没有更好的解决方案? [复制]

如何加快 WordPress 中的 GEO 搜索

如何使用 GEOquery 包提取示例标题(名称)?

两个 GEO 位置之间的距离 [重复]

如何从 google ads api 报告中检索数据(geo_performance_report)