【问题标题】:R: Histogram with both custom breaks and constant widthR:具有自定义中断和恒定宽度的直方图
【发布时间】:2015-07-14 18:35:28
【问题描述】:

我有一些倾斜的数据,想创建一个带有自定义中断的直方图,但希望它实际上看起来可读且具有恒定宽度的 bin(这会偏离 x 轴的比例,但这很好)。有谁知道如何在 ggplot/R 中做到这一点?

这是我不想要的,但我不知道如何使中断不覆盖宽度参数:

library(ggplot2)
test_data = rep(c(1,2,3,4,5,8,9,14,20,42,98,101,175), c(50,40,30,20,10,6,6,7,9,5,6,4,1))
buckets = c(-.5,.5,1.5,2.5,3.5,4.5,5.5,10.5,99.5,200)
q1 = qplot(test_data,geom="histogram",breaks=buckets)
print(q1)

不是我想要的直方图:(

【问题讨论】:

  • 您可以在 base R 中使用 cut() 创建一个代表您的自定义 bin 的因子,然后使用 barplot() 绘制这些 bin 中的计数。
  • 或者坚持使用ggplot 你会做q1 = qplot(cut(test_data, buckets), geom = "histogram")
  • 谢谢你们,这正是我所需要的。
  • @choff 你为什么不把它作为答案发布?
  • @ChristopherBottoms,当然。刚刚做了。

标签: r ggplot2 histogram


【解决方案1】:

按照 ulfelder 的建议,使用 cut():

library(ggplot2)
test_data = rep(c(1,2,3,4,5,8,9,14,20,42,98,101,175),
                c(50,40,30,20,10,6,6,7,9,5,6,4,1))
buckets = c(-.5,.5,1.5,2.5,3.5,4.5,5.5,10.5,99.5,200)
q1 = qplot(cut(test_data, buckets), geom="histogram")
print(q1)

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 2013-02-21
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2011-12-31
    相关资源
    最近更新 更多