简体   繁体   English

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

[英]Creating stacked barplots in R using different variables

I am a novice R user, hence the question. 我是R新手,因此是个问题。 I refer to the solution on creating stacked barplots from R programming: creating a stacked bar graph, with variable colors for each stacked bar . 我指的是使用R编程创建堆叠条形图的解决方案:创建堆叠条形图,每个堆叠条形具有不同的颜色

My issue is slightly different. 我的问题略有不同。 I have 4 column data. 我有4列数据。 The last column is the summed total of the first 3 column. 最后一列是前三列的总和。 I want to plot bar charts with the following information 1) the summed total value (ie 4th column), 2) each bar is split by the relative contributions of each of the three column. 我想用以下信息绘制条形图:1)总和(即第4列),2)每个条形图均被三列中每列的相对贡献除以。

I was hoping someone could help. 我希望有人能提供帮助。

Regards, Bernard 此致,伯纳德

If I understood it rightly, this may do the trick 如果我正确理解,这可能会解决问题

the following code works well for the example df dataframe 以下代码适用于示例df数据帧

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

As you don't want to plot a counter of variables, but the actual value in your dataframe, you need to use the goem_bar(stat="identity") method on ggplot2. 由于您不想绘制变量计数器,而不想绘制数据框中的实际值,因此需要在ggplot2上使用goem_bar(stat =“ identity”)方法。 Some data manipulation is necessary too. 一些数据操作也是必要的。 And you don't need a sum column, ggplot does the sum for you. 而且您不需要求和列,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)

this code generates the plot bellow 此代码生成情节如下

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM