使用 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
表格对象可以绘制为马赛克图。使用plot
. 你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')