首页 > 解决方案 > 如何在ggplot2中为geom_text中的条形图四舍五入数据标签?

问题描述

我正在制作一系列条形图,其中百分比值位于每个条形上方。我想将它四舍五入到小数点后 0 位,但它是小数点后 3 位。这是我正在使用的示例代码

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

在此处输入图像描述

有没有办法将这些四舍五入到最接近的整数,以便条形图没有小数点?

标签: rggplot2labelbar-chart

解决方案


只需accuracy = 1scales::percent函数内添加

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

在此处输入图像描述

要拥有 1 位或 2 位小数,您可以使用accuracy = 0.1accuracy = 0.01。有关详细信息,请访问


推荐阅读