在ggplot2中的条形图上舍入%标签

Bra*_*don 14 r rounding bar-chart ggplot2

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

在此输入图像描述

正如你所看到的,我得到的数字超过了所需的数字,我希望选项(数字= 2)可以做到,但我猜不是.有任何想法吗?

koh*_*ske 15

其实你离那里很近.
这是一个最小的例子:

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

同时,format,round,prettyNum,等,是可用的.

更新:

感谢@Tommy的评论,这里有一个更简单的形式:

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