r - 从 rle() 类对象列表中绘制多个直方图

标签 r plot

我有为数据集中每个单独的 ID 创建的 rle() 类对象,现在我想将它们绘制在单独的直方图中,显示各种长度类的频率,以便了解它们的分布情况,但是我似乎不知道该怎么做。

我通过使用以下代码对具有各种 ID 的数据运行 rle() 函数来获得 rle() 类对象的列表:

list.runs<-dlply(data.1, .(ID), function(x) rle(x$flights))

但这使得无法将数据传输到数据帧中,因为无法将 rle() 对象强制转换为数据帧。因此我将它们取消分类:

list.runs<-dlply(data.1, .(ID), function(x) unclass(rle(x$flights)))

但我无法将此数据放入数据框中,因为列表的长度不同。

runs<-ldply(do.call(data.frame,list.runs))

Error in function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
arguments imply differing number of rows: 14, 13

问题:如何绘制每个单独 ID 的长度值的直方图?

数据(简化):

> dput(data.1)
structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), flights = c(1, 1, 1, 
1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 
0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 
1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 
1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 
1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1)), .Names = c("ID", "flights"
), row.names = c(NA, -100L), class = "data.frame")

最佳答案

我不知道你想做什么,但我会在这里展示如何:

require(plyr)
list.runs <- ddply(data.1, .(ID), function(x) {
    rr <- rle(x$flights)
    data.frame(freq=rr$lengths, xvar=seq_along(rr$lengths))
})

require(ggplot2)
ggplot(data = list.runs, aes(x = factor(xvar), y = freq)) + 
        geom_bar(stat = "identity", aes(fill=factor(ID))) + 
          facet_wrap( ~ ID, ncol=2)

给你:

enter image description here

编辑:根据 OP 的评论:您也可以直接从这些数据中获取。事实上,您不必为您的要求生成“xvar”。来自 list.runs:

ggplot(data = list.runs, aes(x = factor(freq))) + 
     geom_bar(aes(weights = ..count.., fill=factor(ID))) + 
     facet_wrap( ~ ID, ncol=2)

给出:

enter image description here

关于r - 从 rle() 类对象列表中绘制多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363334/

相关文章:

python - Pandas 没有在 y 轴上显示 timedelta 所需的结果

R脚本作为cronjob未执行

python - 如何在 matplotlib 中很好地绘制剪裁的分层艺术家?

Python 箭袋角度问题 : What is the difference between angles ="uv" and angles ="xy"

matlab - 使用 x、y、z 点绘制曲面

r - 在 R 中更改日历热图上的天数顺序

r - 使用 ggplot2 绘图的不规则时间序列未正确缩放并且看起来很拥挤

替换缺失值

r - R Shiny 中带有 leafletProxy 的 Leaflet drawToolbar

r - log-pdf的核估计