【问题标题】:Stacked Bar Chart from List列表中的堆积条形图
【发布时间】:2016-05-31 15:24:10
【问题描述】:

我有以下矩阵

  IdCarrefour 10 11 12 13
1           2  3  8  5 NA
2           4 NA  4  1 NA
3           5 NA NA NA NA
4           6 NA  4  1 NA
5           7 NA NA NA NA

对于每个列,我想要获得多少 NA 和多少非 NA。所以我使用了apply函数:

mTF<-apply(m,2,function(x) table(!is.na(x)))
> str(mTF)
List of 5
 $ IdCarrefour: 'table' int [1(1d)] 5
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr "TRUE"
 $ 10         : 'table' int [1:2(1d)] 4 1
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr [1:2] "FALSE" "TRUE"

mTF 是一个列表。现在我想使用ggplot 绘制一个堆积条形图。

所以我尝试将 mTF 转换为 data.frame。在其他相关帖子的帮助下,我想出了这两种方法:

data.frame(matrix(unlist(mTF), nrow=5, byrow=T),stringsAsFactors=FALSE)
Warning message:
In matrix(unlist(mTF), nrow = 5, byrow = T) :
  data length [8] is not a sub-multiple or multiple of the number of rows [5]

不适合我,因为我对每个级别都没有相同的因素(请参阅警告)

do.call(rbind.data.frame, mTF)

也不起作用,因为它重复了缺少的级别(对于最后一行,我应该有 0 T 和 5 F)。

            c.5L..4L..2L..2L..5L. c.5L..1L..3L..3L..5L.
IdCarrefour                     5                     5
10                              4                     1
11                              2                     3
12                              2                     3
13                              5                     5

那么有没有办法将我的列表 (mTF) 转换为我可以用来绘制的 data.frame?

【问题讨论】:

    标签: r list ggplot2 stacked-chart


    【解决方案1】:

    首先我们需要对您的数据执行一些操作。请注意,我已将您的矩阵转换为名为 dfdata.frame

    df
    
      IdCarrefour X10 X11 X12 X13
    1           2   3   8   5  NA
    2           4  NA   4   1  NA
    3           5  NA  NA  NA  NA
    4           6  NA   4   1  NA
    5           7  NA  NA  NA  NA
    #create new data.frame
    df2 <- rbind(
                stack(apply(df, 2, FUN = function(x) sum(is.na(x)))), #NA
                stack(apply(df, 2, FUN = function(x) sum(!is.na(x)))) #not NA
                )
    df2
    
       values         ind
    1       0 IdCarrefour
    2       4         X10
    3       2         X11
    4       2         X12
    5       5         X13
    6       5 IdCarrefour
    7       1         X10
    8       3         X11
    9       3         X12
    10      0         X13
    #add indicator column
    df2 <- data.frame(df2, Indicator = rep(c('NA','Not NA'), each = 5))
    #remove IdCarrefour
    df2 <- subset(df2, ind != 'IdCarrefour')
    #make plot
    ggplot(df2, aes(x = ind, y = values))+geom_bar(stat = 'identity', aes(fill = Indicator))
    

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 2022-08-12
      • 1970-01-01
      • 2021-07-03
      • 2017-02-26
      • 1970-01-01
      • 2014-02-09
      • 2020-09-14
      相关资源
      最近更新 更多