我有一个数据框:
x <- data.frame(id=letters[1:3],val0=1:3,val1=4:6,val2=7:9)
id val0 val1 val2
1 a 1 4 7
2 b 2 5 8
3 c 3 6 9
我想绘制一个堆积条形图,显示每列的百分比。因此,每个条形代表一行,并且每个条形都有长度,但具有三种不同的颜色,每种颜色代表 val0、val1 和 val2 的百分比。
我尝试寻找它,我只得到绘制堆积图的方法,而不是绘制堆积比例图的方法。
谢谢。
最佳答案
使用ggplot2
对于ggplot2
和geom_bar
- 以长格式工作
- 预先计算百分比
例如
library(reshape2)
library(plyr)
# long format with column of proportions within each id
xlong <- ddply(melt(x, id.vars = 'id'), .(id), mutate, prop = value / sum(value))
ggplot(xlong, aes(x = id, y = prop, fill = variable)) + geom_bar(stat = 'identity')
# note position = 'fill' would work with the value column
ggplot(xlong, aes(x = id, y = value, fill = variable)) +
geom_bar(stat = 'identity', position = 'fill', aes(fill = variable))
# 将返回与上面相同的图
基础R
表格对象可以绘制为马赛克图。使用绘图。你的x
(几乎)是一个表对象
# get the numeric columns as a matrix
xt <- as.matrix(x[,2:4])
# set the rownames to be the first column of x
rownames(xt) <- x[[1]]
# set the class to be a table so plot will call plot.table
class(xt) <- 'table'
plot(xt)
您也可以直接使用mosaicplot
mosaicplot(x[,2:4], main = 'Proportions')
关于r - 如何绘制堆积比例图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051363/