首页 文章

创建堆叠条形图,其中每个堆栈按比例缩放为100%

提问于
浏览
48

我有一个像这样的data.frame:

df <- read.csv(text = "ONE,TWO,THREE
                       23,234,324
                       34,534,12
                       56,324,124
                       34,234,124
                       123,534,654")

我想生成一个百分比条形图,看起来像这样(在LibreOffice Calc中制作):
enter image description here

因此,杆应该标准化,因此所有堆叠具有相同的高度并且总和为100% . 到目前为止,我所能获得的是一个堆积的条形图(不是百分比),使用:

barplot(as.matrix(df))

有帮助吗?

4 回答

  • 12

    您只需要将每个元素除以其列中值的总和 .

    这样做应该足够了:

    data.perc <- apply(data, 2, function(x){x/sum(x)})
    

    请注意,第二个参数告诉 apply 将提供的函数应用于列(使用1将其应用于行) . 然后,匿名函数每次传递一个数据列 .

  • 4

    prop.table是一种获得比例表的友好方式 .

    m <- matrix(1:4,2)
    
     m
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    

    保证金空白为您提供整个表格的比例

    prop.table(m, margin=NULL)
         [,1] [,2]
    [1,]  0.1  0.3
    [2,]  0.2  0.4
    

    给它1给你行比例

    prop.table(m, 1)
          [,1]      [,2]
    [1,] 0.2500000 0.7500000
    [2,] 0.3333333 0.6666667
    

    2是列比例

    prop.table(m, 2)
              [,1]      [,2]
    [1,] 0.3333333 0.4285714
    [2,] 0.6666667 0.5714286
    
  • 12

    克里斯比利是严格的,你只需要列的比例 . 使用您的数据是:

    your_matrix<-( 
                   rbind(
                           c(23,234,324), 
                           c(34,534,12), 
                           c(56,324,124), 
                           c(34,234,124),
                           c(123,534,654)
                        )
                    )
    
     barplot(prop.table(your_matrix, 2) )
    

    给:

    enter image description here

  • 85

    既然你用 ggplot2 标记了这个,到目前为止's a solution using that package (version 0.9.0) in addition to what you'已经得到了 .

    我们使用 geom_barposition 参数设置为 position = "fill" . 如果要使用 position_fill()vjustreverse )的参数,也可以使用 position = position_fill() .

    请注意,您的数据采用'wide'格式,而 ggplot2 要求采用'long'格式 . 因此,我们首先需要 melt 数据 .

    dat <- read.table(text = "    ONE TWO THREE
    1   23  234 324
    2   34  534 12
    3   56  324 124
    4   34  234 124
    5   123 534 654",sep = "",header = TRUE)
    
    #Add an id variable for the filled regions
    library(reshape)
    datm <- melt(cbind(dat, ind = rownames(dat)), id.vars = c('ind'))
    
    library(scales)
    ggplot(datm,aes(x = variable, y = value,fill = ind)) + 
        geom_bar(position = "fill",stat = "identity") +
        # or:
        # geom_bar(position = position_fill(), stat = "identity") 
        scale_y_continuous(labels = percent_format())
    

    enter image description here

相关问题