在一个分面ggplot条形图中y实验室的百分比? [英] percentage on y lab in a faceted ggplot barchart?

查看:126
本文介绍了在一个分面ggplot条形图中y实验室的百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ggplot中做多面我通常会使用百分比来代替计数。

例如

  test1<  -  sample(letters [1: 2],100,replace = T)
test2< - sample(letters [3:8],100,replace = T)
test< - data.frame(cbind(test1,test2) )
ggplot(test,aes(test2))+ geom_bar()+ facet_grid(〜test1)



这很容易,但如果方面A中的N与方面B相比不同,那么我认为比较百分比会更好,这样每个方面的总和就达到100%。



你会怎么做到这一点?

希望我的问题有道理。

此致

解决方案

试试这个:

 #首先创建一个频率为
df < - as.data.frame(with(test,table(test1,test2)))
#或与来自plyr软件包的count()一样,Hadley建议
df< - count(test,vars = c('test1','test2'))
#next:每个组的计算百分比
df < - ddply(df,。(test1),transform,p = Freq / sum(Freq))
#和plot
ggplot(df,aes(test2,p))+ geom_bar + facet_grid(〜test1)



您也可以添加 + scale_y_continuous(formatter =percent)到版本0.9.9的 ggplot2 版本或 + scale_y_continuous(labels = percent_format())的图。

doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

test1 <- sample(letters[1:2], 100, replace=T)
test2 <- sample(letters[3:8], 100, replace=T)
test <- data.frame(cbind(test1,test2))
ggplot(test, aes(test2))+geom_bar()+facet_grid(~test1)

This is very easy but if N is different in facet A compared to facet B, it would be better I think, to compare percentages, in such a way that the each facet sums to 100%.

how would you achieve this?

Hope my question makes sense.

Sincerely.

解决方案

Try this:

# first make a dataframe with frequencies
df <- as.data.frame(with(test, table(test1,test2)))
# or with count() from plyr package as Hadley suggested
df <- count(test, vars=c('test1', 'test2'))
# next: compute percentages per group
df <- ddply(df, .(test1), transform, p = Freq/sum(Freq))
# and plot
ggplot(df, aes(test2, p))+geom_bar()+facet_grid(~test1)

You could also add + scale_y_continuous(formatter = "percent") to the plot for ggplot2 version 0.8.9, or + scale_y_continuous(labels = percent_format()) for version 0.9.0.

这篇关于在一个分面ggplot条形图中y实验室的百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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