我有一个像这样的data.frame:
df <- read.csv(text = "ONE,TWO,THREE
23,234,324
34,534,12
56,324,124
34,234,124
123,534,654")
Run Code Online (Sandbox Code Playgroud)
我想生成一个百分比条形图,看起来像这样(在LibreOffice Calc中制作):

因此,条形应该标准化,因此所有堆叠具有相同的高度并且总和为100%.到目前为止,我所能获得的是一个堆积的条形图(不是百分比),使用:
barplot(as.matrix(df))
Run Code Online (Sandbox Code Playgroud)
有帮助吗?
jor*_*ran 104
由于你使用ggplot2标记了这个,所以除了你到目前为止,使用该软件包(版本0.9.0)的解决方案.
我们使用set 的ggplot参数.如果要使用(和)的参数,也可以使用.positiongeom_barposition = "fill"position = position_fill()position_fill()vjust
请注意,您的数据采用"宽"格式,而reverse要求采用"长"格式.因此,我们首先需要ggplot2数据.
library(ggplot2)
library(dplyr)
library(tidyr)
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 and reshape
datm <- dat %>%
mutate(ind = factor(row_number()) %>%
gather(variable, value, -ind)
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 = scales::percent_format())
Run Code Online (Sandbox Code Playgroud)

ale*_*mol 15
克里斯比利是严格的,你只需要列的比例.使用您的数据是:
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) )
Run Code Online (Sandbox Code Playgroud)

Chr*_*ley 13
prop.table是获得表格比例的友好方式.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Run Code Online (Sandbox Code Playgroud)
保证金空白为您提供整个表格的比例
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Run Code Online (Sandbox Code Playgroud)
给它1给你行比例
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
Run Code Online (Sandbox Code Playgroud)
2是列比例
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
Run Code Online (Sandbox Code Playgroud)
您只需要将每个元素除以其列中值的总和。
这样做就足够了:
data.perc <- apply(data, 2, function(x){x/sum(x)})
Run Code Online (Sandbox Code Playgroud)
请注意,第二个参数告诉apply将提供的函数应用于列(使用 1 将其应用于行)。然后,匿名函数一次传递每个数据列。
| 归档时间: |
|
| 查看次数: |
108368 次 |
| 最近记录: |