创建堆叠的barplot,其中每个堆栈缩放到总和100% [英] Create stacked barplot where each stack is scaled to sum to 100%
问题描述
我有这样的数据框:
df < - read.csv(text =ONE,TWO ,$ $ b $ 23,234,324
34,534,12
56,324,124
34,234,124
123,534,654)
我想生成一个百分比条形图,看起来像这样(用LibreOffice Calc制作):
因此,钢筋应该是标准化的,所以所有的堆垛都有相同的高度和总和为100%。到目前为止,我所能得到的是一个堆积的barplot(不是百分比),使用:
pre $ barplot(as.matrix (df))
有什么帮助吗?
由于您使用 ggplot2 标记了此处,因此使用该包(0.9.0版)我们使用位置
参数 geom_bar
设置为 position =fill
。如果你想使用 position_fill()
(<$ c)的参数,你也可以使用 position = position_fill()
$ c> vjust 和 reverse
)。
请注意,您的数据位于'宽'格式,而 ggplot2
要求它是'长'格式。因此,我们首先需要融化
数据。
dat< - read.table(text =一两三$ b $ 1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534
为已填充区域添加一个id变量
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)+
#或:
#geom_bar(position = position_fill(),stat =identity )
scale_y_continuous(labels = percent_format())
I have a data.frame like this:
df <- read.csv(text = "ONE,TWO,THREE
23,234,324
34,534,12
56,324,124
34,234,124
123,534,654")
I want to produce a percent bar plot which looks like this (made in LibreOffice Calc):
Thus, the bars should be standarized so all stacks have the same height and sums to 100%. So far all I have been able to get is is a stacked barplot (not percent), using:
barplot(as.matrix(df))
Any help?
Since you tagged this with ggplot2 here's a solution using that package (version 0.9.0) in addition to what you've gotten so far.
We use the position
argument of geom_bar
set to position = "fill"
. You may also use position = position_fill()
if you want to use the arguments of position_fill()
(vjust
and reverse
).
Note that your data is in a 'wide' format, whereas ggplot2
requires it to be in a 'long' format. Thus, we first need to melt
the data.
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())
这篇关于创建堆叠的barplot,其中每个堆栈缩放到总和100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!