ggplot2 条形图上的舍入百分比标签

发布于 2024-12-06 03:36:15 字数 909 浏览 2 评论 0原文

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

在此处输入图像描述

正如你所看到的,我得到的数字比需要的要多,我希望有选项( digits=2) 会这样做,但我想不会。有什么想法吗?

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

enter image description here

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ま昔日黯然 2024-12-13 03:36: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")

此外,还可以使用 formatroundprettyNum 等。

更新:

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

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

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")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文