【问题标题】:Why does R ignore binwidth, bins in ggplot geom_histogram?为什么R忽略ggplot geom_histogram中的binwidth,bin?
【发布时间】:2017-06-26 03:31:50
【问题描述】:

我正在尝试在数据框的一列中绘制值的直方图。我尝试设置 bin 或 binwidth 参数,但无济于事。 R 在构建绘图时说,“忽略未知参数:binwidth, bins, pad”。

ggplot(data=subset(flights, Distance < quantile(flights$Distance, 0.75)))+ geom_histogram(aes(x=Distance), stat='count', binwidth=100)

要绘制的变量是整数向量,即飞行距离。

我尝试将数据类型从整数更改为数字。

flights$Distance &lt;- as.numeric(as.character(flights$Distance))

我在较小的样本上进行了尝试,得到了相同的信息。

df &lt;- data.frame(Distance=c(2,3,4,5,3,2,4,5,6,7,5,4,9,8,7,6,5,4,3,4,5,6,5))

ggplot(data=df)+ geom_histogram(aes(x=Distance), stat='count', binwidth=2)

为什么 ggplot 忽略两个可能的 bin 参数?

【问题讨论】:

  • 只需从对geom_histogram 的调用中删除stat='count'geom_histogram 默认使用 stat="bin",这就是您想要的直方图统计数据。

标签: r ggplot2


【解决方案1】:

也许this 会有所帮助:

通过除法可视化单个连续变量的分布 将 x 轴放入箱中并计算每个箱中的观察次数 斌。直方图 (geom_histogram) 用条形图显示计数; 频率多边形(geom_freqpoly),用线条显示计数。 当你想比较频率多边形时更合适 跨类别变量的水平分布。 stat_bin 仅适用于连续 x 数据。如果您的 x 数据是离散的, 您可能想使用 stat_count。

ggplot()+
  geom_histogram(data = df, aes(x=Distance), binwidth = 3) +
                 stat_count()

【讨论】:

  • 如果您想要直方图,stat_count() 在这里是多余的。 (尽管对于整数数据,stat_count 会给你相当于 binwidth=1 的直方图。)如果你将 fill="red" 添加到 geom_histogram,你会看到 stat_count() 正在放置一个条形图在直方图之上。您只是看不到它,因为 geom_histogramstat_count 使用相同的默认填充颜色。
  • 有趣。是否有可能看到stat_count() 如何将条形图“置于”直方图的顶部?我尝试设置fill = "red",但没有注意到任何内容。
  • 啊,这是因为您将数据和美学放在 geom_histogram 中,而不是放在主 ggplot 调用中。所以stat_count() 完全没有做任何事情,因为它不了解数据框或美学。对不起,我没有仔细看你的代码。如果您将数据框和aes 放在主 ggplot 调用中,您将看到两组条形图。
猜你喜欢
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
相关资源
最近更新 更多