【问题标题】:Plotting a histogram with custom breaks绘制带有自定义中断的直方图
【发布时间】:2014-10-27 06:28:11
【问题描述】:

我有一个像这样的向量:

K <- rnorm(10000, mean=100)

我想创建一个 K 的直方图,其中包含 &lt;20, 20-50, 50-75, 75-99, =100, &gt;400 等自定义中断(和标签)。

有什么想法吗?

【问题讨论】:

  • “自定义中断”在哪里是指“自定义中断”? @jbaums 所说的,只需使用自定义 hist(..., breaks=...) 参数即可。

标签: r plot histogram


【解决方案1】:

使用base 绘图,您最好先使用cutting 向量,然后对表格使用barplotplot 方法。

例如:

K <- rnorm(10000, mean=100, sd = 100)
K.cut <- cut(K, c(-Inf, 20, 50, 75, 100, 400, Inf))

plot(table(K.cut), xaxt='n', ylab='K')
axis(1, at=1:6, labels=c('< 20', '20-50', '50-75', '75-100', '100-400', '> 400'))
box(bty='L')

xax <- barplot(table(K.cut), xaxt='n')
axis(1, at=xax, labels=c('< 20', '20-50', '50-75', '75-100', '100-400', '> 400'))
box(bty='L')

请注意,默认情况下,cut 包括每个 bin 中的上限(但不包括下限),例如,20-50 bin 包括任何 50,但 20 将包含在下相邻 bin 中。

【讨论】:

    【解决方案2】:

    试试ggplot版本:

    library(ggplot)
    ggplot()+ geom_histogram(aes(K))
    

    许多选项可用于调整。

    【讨论】:

    • 使用 ggplot(),这里需要的是scale_x_continuous(breaks=c(20,50,75,99,100,400))
    • 我认为“自定义”中断“喜欢”