在一个刻面的ggplot条形图中y实验室的百分比?

And*_*eas 32 r ggplot2

在ggplot中做facet我经常喜欢使用百分比而不是计数.

例如

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)
Run Code Online (Sandbox Code Playgroud)

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

你会怎么做到这一点?

希望我的问题有道理.

真诚.

Jam*_*mes 46

这是一个内部ggplot方法,使用..count....PANEL..:

ggplot(test, aes(test2)) + 
    geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])) + 
    facet_grid(~test1)
Run Code Online (Sandbox Code Playgroud)

由于这是在运行中计算的,因此对于绘图参数的更改应该是稳健的.

  • 当然.这是[问题](http://stackoverflow.com/questions/20600900/r-faceted-bar-chart-with-percentages-labels-independent-for-each-plot)我把它留在这里供将来参考. (2认同)

dar*_*zig 21

试试这个:

# 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)
Run Code Online (Sandbox Code Playgroud)

替代文字

您还可以添加ggplot2版本0.8.9或版本0.9.0 + scale_y_continuous(formatter = "percent")的图表.+ scale_y_continuous(labels = percent_format())

  • 尝试使用`count`而不是`as.data.frame(table(...))` - 它更快,并且不会将所有制表变量转换为因子. (2认同)

dar*_*zig 7

一个非常简单的方法:

ggplot(test, aes(test2)) + 
    geom_bar(aes(y = (..count..)/sum(..count..))) + 
    facet_grid(~test1)
Run Code Online (Sandbox Code Playgroud)

所以我只将geom_bar的参数更改为aes(y = (..count..)/sum(..count..)).将ylab设置为NULL并指定格式化程序后,您可以获得:

ggplot(test, aes(test2)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) + 
    facet_grid(~test1) +
    scale_y_continuous('', formatter="percent")
Run Code Online (Sandbox Code Playgroud)

更新 请注意,虽然formatter = "percent")适用于ggplot2版本0.8.9,但在0.9.0中你需要类似的东西scale_y_continuous(labels = percent_format()). 替代文字

  • 在ggplot2的0.9.3版本中,这不起作用.而不是将每个方面加到100%,这将*all*facets添加到100%. (6认同)
  • 实际上是scale_y_continuous(labels = percent)(使用scale包) (4认同)
  • 我之前的评论不正确.我看到一个非常奇怪的行为:从一个新的R会话开始,这是有效的.从一个加载了大量库的项目开始,这不起作用.而不是将每个方面加到100%,这将*all*facets添加到100%.看起来像ggplot2中的一个错误 - 有些东西让人感到困惑. (2认同)