在ggplot2的条形图上舍入%标签 [英] Rounding % Labels on bar chart in ggplot2

查看:217
本文介绍了在ggplot2的条形图上舍入%标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<因子(Q1),数据=调查,几何=直方图,填充=因子(Q1),ylim = c(0,300))

options(digits = 2)

q1 + geom_bar(color =black)+
stat_bin(aes(label = .. count ..),vjust = - 2,geom =text,position =identity)+
stat_bin(geom =text,aes(label = paste(.. count ../ sum(.. count ..)* 100, %),vjust = -0.75))+
labs(x =问题#1:\ n 0 =没有回应,1 =完全不熟悉,5 =非常熟悉)+
opts(title =问题#1的直方图:\ n您是否熟悉术语'生物基产品'?,
legend.position =none,
plot.title = theme_text(size = 16,vjust = 1,face =bold),
axis.title.x = theme_text(size = 14),axis.text.x = theme_text(size = 12),
axis.title.y = theme_text(size = 14,angle = 90),axis.text.y = theme_text(size = 12))



正如你所见,我是getti ng的方式比需要更多的数字,我希望选项(数字= 2)会做到这一点,但我猜不是。任何想法?

解决方案

其实你很接近那里。

这里是一个简单的例子:

  df < -  data.frame(x = factor(sample(5,99,T)))
ggplot(df,aes(x))+
stat_bin(aes(label = paste(sprintf(%。02f,..count ../ sum(.. count ..)* 100) )),
geom =text)

同样, format round prettyNum 等等。



更新:

感谢@Tommy的评论,这里si更简单:

  ggplot(df,aes(x))+ 
stat_bin(aes(label = sprintf(%。02f% %,..count ../ sum(.. count ..)* 100)),
geom =text)


q1 <- qplot(factor(Q1), data=survey, geom="histogram", fill=factor(Q1), ylim=c(0,300))

options(digits=2)

q1 + geom_bar(colour="black") + 
stat_bin(aes(label=..count..), vjust=-2, geom="text", position="identity") +
stat_bin(geom="text", aes(label=paste(..count../sum(..count..)*100,"%"), vjust=-0.75)) +
labs(x="Question # 1:\n 0 = Didn't respond, 1 = Not at all familiar, 5 = Very familiar") +
opts(title="Histogram of Question # 1:\nHow familiar are you with the term 'Biobased Products'?", 
    legend.position = "none",
    plot.title = theme_text(size = 16, , vjust = 1, face = "bold"), 
    axis.title.x =theme_text(size=14), axis.text.x=theme_text(size=12),
    axis.title.y=theme_text(size=14, angle=90), axis.text.y=theme_text(size=12))

As you can see I'm getting way more digits than what is needed, I was hoping the options(digits=2) would do it but I guess not. Any ideas?

解决方案

Actually you are very close to there.
Here is a minimal example:

df <- data.frame(x = factor(sample(5, 99, T)))
ggplot(df, aes(x)) + 
  stat_bin(aes(label = paste(sprintf("%.02f", ..count../sum(..count..)*100), "%")), 
           geom="text")

also, format, round, prettyNum, etc, is available.

UPDATED:

Thanks to @Tommy 's comment, here si a more simple form:

ggplot(df, aes(x)) + 
 stat_bin(aes(label = sprintf("%.02f %%", ..count../sum(..count..)*100)),
     geom="text")

这篇关于在ggplot2的条形图上舍入%标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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