Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

r - how to put exact number of decimal places on label ggplot bar chart

How can I specify the exact number of decimal places on ggplot bar chart labels?

The data:

strefa  <- c(1:13)
a       <- c(3.453782,3.295082,3.137755,3.333333,3.500000,3.351351,3.458824,3.318681,3.694175,3.241379,3.138298,3.309524,3.380000)
srednie <- data.frame(strefa,a)

The code is:

ggplot(srednie, aes(x=factor(strefa), y=a, label=round(a, digits = 2))) +
  geom_bar(position=position_dodge(), stat="identity",  colour="darkgrey", width = 0.5) +
  theme(legend.position="none",axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
  geom_text(size = 4, hjust = 1.2) +
  coord_flip(ylim = c(1,6))+
  xlab("") +
  ylab("")

As you can see, on bars entitled 5 and 2 the labels are limited to the 1st decimal place. How to show 2 decimal places even if there is i.e. 3.000000 or 5.999999? In such a cases I would like to show 3.00 and 6.00.

I tried to use as a aes parameter label=round(a, digits = 2) but it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try the following as it rounds to two digits and prints two digits after the decimal.

ggplot(srednie, aes(x=factor(strefa), y=a, label=sprintf("%0.2f", round(a, digits = 2)))) +
  geom_bar(position=position_dodge(), stat="identity",  colour="darkgrey", width = 0.5) +
  theme(legend.position="none",axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
  geom_text(size = 4, hjust = 1.2) +
  coord_flip(ylim = c(1,6))+
  xlab("") +
  ylab("")

The only modification was changing your code from

round(a, digits = 2)

to

sprintf("%0.2f", round(a, digits = 2))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...