r - 如何绘制堆积比例图?

标签 r plot ggplot2 dataframe stacked

我有一个数据框:

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

对于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')

enter image description here

 # 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)

enter image description here

您也可以直接使用mosaicplot

mosaicplot(x[,2:4], main = 'Proportions')

关于r - 如何绘制堆积比例图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051363/

相关文章:

r - (R) 如何将不同类型的对象组合成一行,同时保持其类型?

r - 在 R 中处理个人功能的最佳实践

python - 在 df.plot(kind ='hist') 中指定 bean 的数量

删除或隐藏 R ggplot2/factoextra 图上的零线

r - 图例在 ggplot2 密度图中不显示线型

r - 在 R 中传播数据

r - 当未找到给定函数的绑定(bind)时,如何防止箭头将数据拉入 R?

r - 如何用ggplot绘制回归线?

python - 图例中的标签顺序不正确

r - 将 geom_point 与 geom_polygon 分组