R ggplot2堆叠条形图,带有多个类别变量的百分比 [英] R ggplot2 stacked barplot by percentage with several categorical variables
问题描述
这是一个简单的问题,但是我很难理解ggplot2所需的格式:
This is a simple question, but I'm having difficulty understanding the format required by ggplot2:
我有以下 data.table 在R中,
print(dt)
ID category A B C totalABC
1: 10 group1 1 3 0 4
2: 11 group1 1 11 1 13
3: 12 group2 15 20 2 37
4: 13 group2 6 12 2 20
5: 14 group2 17 83 6 106
...
我的目标是创建一个比例堆叠的条形图,如下例所示: https://rpubs.com/escott8908/RGC_Ch3_Gar_Graphs
My goal is to create a proportional stacked bar graph as in this example: https://rpubs.com/escott8908/RGC_Ch3_Gar_Graphs
其中X / totalABC的百分比,其中i s category_type
A,B或C。我也想按类别执行此操作,例如x轴值应为 group1
, group2
等。
where the percentages of X/totalABC, where X is category_type
either A, B, or C. I would also like to perform this by category, e.g. the x-axis values should be group1
, group2
, etc.
作为一个具体示例,在 group1
的情况下,共有4 + 13 = 17个元素。
As a concrete example, in the case of group1
, there are 4+13=17 total elements.
百分比将为 percent_A = 11.7%,percent_B = 82.3%,percent_C = 5.9%
正确的ggplot2解决方案似乎是:
The correct ggplot2 solution appears to be:
library(ggplot2)
pp = ggplot(dt, aes(x=category, y=percentage, fill=category_type)) +
geom_bar(position="dodge", stat="identity")
我的困惑:如何创建与三个类别值相对应的单个 percentage
列?
My confusion: how would I create a single percentage
column that corresponds to three categorical values?
如果以上内容不正确,我该如何格式化 data.table
来创建堆叠的条形图?
If the above is incorrect, how would I format my data.table
to create the stacked barplot?
推荐答案
这是一个解决方案:
require(data.table)
require(ggplot2)
require(dplyr)
melt(dt,measure.vars = c("A","B","C"),
variable.name = "groups",value.name = "nobs") %>%
ggplot(aes(x=category,y=nobs,fill=groups)) +
geom_bar(stat = "identity",position="fill")
这篇关于R ggplot2堆叠条形图,带有多个类别变量的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!