堆积比例图如何绘制? [英] How to plot stacked proportional graph?

查看:407
本文介绍了堆积比例图如何绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

  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


  1. 格式

  2. 预先计算百分比

例如

 库(reshape2)
库(plyr)
#长格式,每个id中的比例列为
xlong< dd((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'将与值列一起使用
ggplot(xlong,aes(x = id,y = value,fill = va可以)
geom_bar(stat ='identity',position ='fill',aes(fill = variable))



#将返回与上述相同的情节



base R



对象可以绘制为马赛克图。使用 plot 。您的 x 是(几乎)一个表对象

 #获取数字列作为矩阵
xt < - as.matrix(x [,2:4])
#将rownames设置为x
rownames(xt)的第一列x [[1]]
#将类设置为表,所以绘图将调用plot.table
类(xt)< - 'table'
plot(xt)



您还可以直接使用 mosaicplot

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


I have a data frame:

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

I want to plot a stacked bar plot that shows the percentage of each columns. So, each bar represents one row and and each bar is of length but of three different colors each color representing percentage of val0, val1 and val2.

I tried looking for it, I am getting only ways to plot stacked graph but not stacked proportional graph.

Thanks.

解决方案

Using ggplot2

For ggplot2 and geom_bar

  1. Work in long format
  2. Pre-calculate the percentages

For example

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

# will return the same plot as above

base R

A table object can be plotted as a mosaic plot. using plot. Your x is (almost) a table object

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

you could also use mosaicplot directly

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

这篇关于堆积比例图如何绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆