【问题标题】:Rounding % Labels on bar chart in ggplot2ggplot2中条形图上的四舍五入%标签
【发布时间】:2011-11-22 22:19:59
【问题描述】:
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))

如您所见,我得到的数字比需要的多,我希望 options(digits=2) 能做到,但我想不会。有什么想法吗?

【问题讨论】:

  • 你试过用round()对它们进行四舍五入吗?
  • 是的,这就是诀窍!谢谢。

标签: r ggplot2 bar-chart rounding


【解决方案1】:

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

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

还可以使用formatroundprettyNum 等。

更新:

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

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

【讨论】:

  • 为什么同时使用pastesprintf?类似于sprintf("%.02f %%", pi) 的东西就足够了。
猜你喜欢
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2023-04-04
相关资源
最近更新 更多