首页 文章

使用不同的变量在R中创建堆积条形图

提问于
浏览
0

我是新手R用户,因此问题 . 我参考了从R programming: creating a stacked bar graph, with variable colors for each stacked bar创建堆积条形图的解决方案 .

我的问题略有不同 . 我有4列数据 . 最后一列是前3列的总和 . 我想绘制条形图,其中包含以下信息:1)总计的总值(即第4列),2)每个柱子由三列中每一列的相对贡献分开 .

我希望有人可以提供帮助 .

此致,伯纳德

1 回答

  • 0

    如果我理解正确,这可能会成功

    以下代码适用于示例df dataframe

    df <-  a   b    c   sum
           1    9   8   18
           3    6   2   11
           1    5   4   10
          23    4   5   32
           5    12  3   20
           2    24  1   27
           1    2   4   7
    

    由于您不想绘制变量计数器,而是绘制数据帧中的实际值,因此需要在ggplot2上使用goem_bar(stat =“identity”)方法 . 一些数据操作也是必要的 . 而且你不需要和列,ggplot会为你做总和 .

    df <- df[,-ncol(df)]            #drop the last column (assumed to be the sum one)
    df$event <- seq.int(nrow(df))   #create a column to indicate which values happaned on the same column for each variable
    df <- melt(df, id='event')      #reshape dataframe to make it readable to gpglot
    
    px = ggplot(df, aes(x = event, y = value, fill = variable)) + geom_bar(stat = "identity")
    print (px)
    

    此代码生成下图

    enter image description here

相关问题