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

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

问题描述

在 ggplot 中做方面我经常希望使用百分比而不是计数.

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

例如

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 方面的 N 不同,我认为最好比较百分比,使每个方面的总和为 100%.

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?

希望我的问题有意义.

真诚的.

推荐答案

试试这个:

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

您还可以将 + scale_y_continuous(formatter = "percent") 添加到 ggplot2 0.8.9 版的绘图中,或 + scale_y_continuous(labels = percent_format()) 适用于 0.9.0 版.

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天全站免登陆