简体   繁体   English

如何在 ggplot2 的 geom_text 中对条形 plot 的数据标签进行四舍五入?

[英]How to round off data labels for a bar plot in geom_text in ggplot2?

I'm making a series of bar charts where the percent value is placed above each bar.我正在制作一系列条形图,其中百分比值位于每个条形上方。 I'd like to round this to 0 decimal places, but it comes to 3 decimal place.我想将它四舍五入到小数点后 0 位,但它是小数点后 3 位。 Here's an example code I am using这是我正在使用的示例代码

g1 <- ggplot(mydata, aes(x=PF.Score))+
  geom_bar(color="Blue", fill="skyblue")+
  geom_text(stat="count", aes(label=scales::percent(..prop..), group=1), size =3, vjust=-0.3)+
  ylab("Count of Suppliers")+
  xlab("D&B Score of Suppliers")+
  ggtitle("D&B Score distribution of suppliers")+
  theme_classic()

在此处输入图像描述

Is there a way to round these to the nearest whole number, so that the bars are labelled with no decimal?有没有办法将这些四舍五入到最接近的整数,以便条形图没有小数点?

Just add accuracy = 1 within scales::percent function like只需在scales::percent function 之内添加accuracy = 1

ggplot(iris, aes(x=Sepal.Width))+
  geom_bar(color="Blue", fill="skyblue")+
  geom_text(stat="count", aes(label=scales::percent(..prop.., accuracy = 1), group=1), size =3, vjust=-0.3)+
  ylab("Count of Suppliers")+
  xlab("D&B Score of Suppliers")+
  ggtitle("D&B Score distribution of suppliers")+
  theme_classic()

在此处输入图像描述

To have 1 or 2 decimals you can use accuracy = 0.1 or accuracy = 0.01 .要拥有 1 或 2 位小数,您可以使用accuracy = 0.1accuracy = 0.01 For details visit this .有关详细信息,请访问

Your y axis is count, but your bar label is percentages.您的 y 轴是计数,但您的条形 label 是百分比。 That is why they don't match.这就是为什么他们不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM