【问题标题】:How to plot stacked proportional graph?如何绘制堆积比例图?
【发布时间】:2013-04-17 04:15:08
【问题描述】:

我有一个数据框:

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 的百分比。

我试着寻找它,我得到的只是绘制堆叠图的方法,而不是堆叠比例图。

谢谢。

【问题讨论】:

  • 你的意思是每个条的长度应该相同吗?

标签: r plot ggplot2 dataframe stacked


【解决方案1】:

使用 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')

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

【讨论】:

  • 谢谢。我们如何改变列的宽度?我有很多列,所以列宽非常小。另外我们如何改变 X 轴标签的方向。?
  • 请注意 geom_bar() 接受参数 position="fill" 这将允许您跳过 ddply 步骤并直接使用熔化的 data.frame。
猜你喜欢
  • 1970-01-01
  • 2018-06-05
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多