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

How do I set ggplot2 binwidth in geom_histogram when using scale_x_log10?

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

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

我不想使用解决方法的一个原因是我不喜欢它;似乎应该有一种更好的方法内置到 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 是多少(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。

尝试输入总宽度的一小部分,这样 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()