Rounding % Labels on bar chart in ggplot2

孤者浪人 提交于 2019-12-30 07:59:23

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/7516861/rounding-labels-on-bar-chart-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!