Sourabh_me
Sourabh_me

Reputation: 13

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

enter image description here

Is there a way to round these to the nearest whole number, so that the bars are labelled with no decimal?

Upvotes: 1

Views: 2916

Answers (2)

JenYen
JenYen

Reputation: 1

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

Upvotes: 0

UseR10085
UseR10085

Reputation: 8136

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

enter image description here

To have 1 or 2 decimals you can use accuracy = 0.1 or accuracy = 0.01. For details visit this.

Upvotes: 1

Related Questions