简体   繁体   中英

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

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 . For details visit this .

Your y axis is count, but your bar label is percentages. That is why they don't match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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