R中的直方图(ggplot)-binwidth不起作用

Posted

技术标签:

【中文标题】R中的直方图(ggplot)-binwidth不起作用【英文标题】:Histogram (ggplot) in R - binwidth not working 【发布时间】:2021-08-04 21:20:12 【问题描述】:

嘿,我有以下代码:

df = data.frame(X = rnorm(40), Y = rep(c("A", "B"), 20))
ggplot() + geom_histogram(data = df, aes(x = X, fill = factor(Y)), stat = "count", position = "dodge", bins = 5) + theme_bw()

我的目标是将X 划分为 5 个 bin 并绘制直方图,我们将在其上看到每个 bin 中 "A""B" 的数量。为什么这段代码不起作用,我应该改变什么?因为bins 不起作用:(

【问题讨论】:

你有什么stat = "count"?这会干扰默认的直方图统计信息。您正在尝试创建一个闪避直方图?这很平常。你真的只想要一个闪避的条形图吗? 【参考方案1】:

不要使用stat = "count"

library(ggplot2)
df = data.frame(X = rnorm(40), Y = rep(c("A", "B"), 20))
ggplot() +
  geom_histogram(
    data = df,
    aes(x = X, fill = factor(Y)),
    #stat = "count",
    position = "dodge",
    bins = 5
  ) +
  scale_fill_manual(values = c("blue", "orange")) +
  theme_bw()

【讨论】:

谢谢!你能告诉我如何减少列的宽度(因为现在列之间没有空间)和列的颜色(例如从红色和绿色到蓝色和橙色) 我在一行中添加了scale_fill_manual(values = c("blue", "orange")) 来更改颜色。请参阅here 以了解将条形分开的策略。 ggplot2 documentation and materials 也很有帮助。

以上是关于R中的直方图(ggplot)-binwidth不起作用的主要内容,如果未能解决你的问题,请参考以下文章

R语言与医学统计图形-14ggplot2几何对象之直方密度图

使用 stat_bin ggplot 的颜色直方图条

如何在 ggplot2 直方图中指定 x 轴?

R语言:qplot()中如何使用fill自定义颜色

为 R 中的 facet_wrap 直方图的每个图分配自定义颜色 - ggplot

使用ggplot将直方图转换为r中的小提琴图