【问题标题】:Using cut() with a histogram使用带有直方图的 cut()
【发布时间】:2016-12-17 17:12:38
【问题描述】:

下面的代码绘制了一个带有阴影区域的直方图,表示比平均值小 2 个标准差、比平均值大 1 个标准差等。

但是,请注意,在直方图的某些 bin 中,有 2 种不同的颜色。是否可以创建只包含 1 种颜色的 bin?

set.seed(1)
df <- data.frame(x = rnorm(10000, mean = 23, sd = 1))

ndist_probs <- c(0, 0.025, 0.16, 0.5, 0.84, 0.975, 1)

ndist_labels <- c("inf-2SD", "2-1SD", "1SD-mean", "mean-1SD", "1-2SD", "2SD-inf")

ndist_breaks <- quantile(df$x, ndist_probs)

df$ndist_breaks <- cut(df$x, breaks = ndist_breaks, ndist_labels)

library(ggplot2)
ggplot(df, aes(x)) + geom_histogram(aes(fill = ndist_breaks))

【问题讨论】:

  • 您需要设置直方图中断以与您的切割值对齐。不确定这可以在 geom_histogram 中完成,但您可以预先计算然后使用 geom_bar
  • 也许ggplot(df, aes(x)) + geom_histogram(aes(fill = ndist_breaks), binwidth = 0.005) ?

标签: r ggplot2 statistics histogram distribution


【解决方案1】:

您可以将数据四舍五入到一位小数。

df <- data.frame(x = round(rnorm(100000, mean = 23, sd = 1),1))

如果您现在将直方图中的 binwidth 设置为 0.1,您将获得所需的结果

ggplot(df, aes(x)) + geom_histogram(aes(fill = ndist_breaks),binwidth = 0.1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多