如何绘制堆积比例图?

Rac*_*wal 2 plot r stacked ggplot2 dataframe

我有一个数据框:

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
Run Code Online (Sandbox Code Playgroud)

我想绘制一个堆积条形图,显示每列的百分比.因此,每个条形代表一行,并且每个条形具有长度但具有三种不同颜色,每种颜色代表val0,val1和val2的百分比.

我试着寻找它,我只能获得绘制堆积图但不是堆积比例图的方法.

谢谢.

mne*_*nel 5

使用ggplot2

ggplot2geom_bar

  1. 以长格式工作
  2. 预先计算百分比

例如

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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

 # 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))
Run Code Online (Sandbox Code Playgroud)

#将返回与上面相同的图

基地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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你也可以mosaicplot直接使用

mosaicplot(x[,2:4], main = 'Proportions')
Run Code Online (Sandbox Code Playgroud)