Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Limit the decimals in histogram labels

I am trying to add data label on a histogram but would like to see limited decimal. Current code is as below:

label =  after_stat(scales::percent(cumsum((count / sum(count))))))

It works fine, but returns different number of decimals depending chart variable data plotted.

Then I referred this link: how to put exact number of decimal places on label ggplot bar chart and modified code as below:

   label =  after_stat(sprintf("%0.f",round(scales::percent(cumsum((count / sum(count)))),digits=2)))

Error in round(scales::percent(cumsum((count/sum(count))))) : non-numeric argument to mathematical function

Can you please suggest right way to trim/round decimal to say 2 places?. Thanks.

question from:https://stackoverflow.com/questions/65912671/limit-the-decimals-in-histogram-labels

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

1 Answer

0 votes
by (71.8m points)

You can pass "accuracy" to scales::percent, e.g.

library(scales)
count = seq(0, 10, 1)
label = scales::percent(cumsum((count / sum(count))), accuracy = 0.001)
label
>[1] "0.000%"   "1.818%"   "5.455%"   "10.909%"  "18.182%" 
>[6] "27.273%"  "38.182%"  "50.909%"  "65.455%"  "81.818%" 
>[11] "100.000%"

label = scales::percent(cumsum((count / sum(count))), accuracy = 0.01)
label
>[1] "0.00%"   "1.82%"   "5.45%"   "10.91%"  "18.18%" 
>[6] "27.27%"  "38.18%"  "50.91%"  "65.45%"  "81.82%" 
>[11] "100.00%"

So, with your data, I think this should work:

label =  after_stat(scales::percent(cumsum((count / sum(count))), accuracy = 0.01))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...