在 ggplot2 中显示频率和条形图 [英] Show frequencies along with barplot in ggplot2

查看:51
本文介绍了在 ggplot2 中显示频率和条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在条形图中显示频率......好吧,我希望它们在图表中某处:条形下方、条形内、条形上方或图例区域中.我记得(我可能错了)它可以在 ggplot2 中完成.这可能很容易……至少看起来很容易.代码如下:

I'm trying to display frequencies within barplot ... well, I want them somewhere in the graph: under the bars, within bars, above bars or in the legend area. And I recall (I may be wrong) that it can be done in ggplot2. This is probably an easy one... at least it seems easy. Here's the code:

p <- ggplot(mtcars)
p + aes(factor(cyl)) + geom_bar()

是否有可能将频率嵌入图表中?

Is there any chance that I can get frequencies embedded in the graph?

推荐答案

geom_text 是基础图形中 text 的类似物:

geom_text is tha analog of text from base graphics:

p + geom_bar() + stat_bin(aes(label=..count..), vjust=0, 
                          geom="text", position="identity")

如果要调整标签的 y 位置,可以在 stat_bin 中使用 y= 美学:例如,y=..count..+1 会将标签放在条形上方一个单位.

If you want to adjust the y-position of the labels, you can use the y= aesthetic within stat_bin: for example, y=..count..+1 will put the label one unit above the bar.

如果您在内部使用 geom_textstat="bin",上述方法也适用.

The above also works if you use geom_text and stat="bin" inside.

这篇关于在 ggplot2 中显示频率和条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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