1

I am plotting median values across using geom_raster in ggplot and am placing data labels using the main aesthetic line and rounding to the hundredth decimal, similar to:

ggplot(data, aes(x=var1,y=var2, label=round(median,2)))

Unfortunately if the hundredth ends in a 0, it truncates to the tenth decimal. In the below image, you can see this issue a couple of places, such as in the top right corner with two values of 0.3.

I tried label=signif(round(k_median,2),2) which did not solve the issue and inappropriately truncates values >1 to the hundredth. I also tried putting the label in the geom_text line (i.e. ggplot(...) + geom_text(aes(label=round(k_median,2)),...) but that also resulted in the same issue.

What I am doing wrong? Is there an alternative way to solve this issue?

Below is my full code that created the figure:

ggplot(subset(sims.summary,type==2 & k_median<3),aes(x=p1,y=p2, label=round(k_median,2)))+ 
    geom_raster(aes(fill = k_median),hjust=0, vjust=0)+
    scale_fill_distiller(palette = "Spectral", direction = -1)+
    xlab("Passive Probability")+ylab("Active Probability")+
    scale_x_continuous(limits=c(0,1),breaks=seq(0,1, by=0.1))+
    scale_y_continuous(limits=c(0,1),breaks=seq(0,1, by=0.1))+
    annotate("rect", xmin = 0.1,xmax=0.2,ymin = 0.5, ymax=1, fill="#9E0142")+
    annotate("rect", xmin = 0.2,xmax=0.3,ymin = 0.9, ymax=1, fill="#9E0142")+
    annotate("rect", xmin = 0,xmax=0.1,ymin = 0.2, ymax=1, fill="#9E0142")+
    geom_text(size=3, hjust=2, vjust=3.5)+
    theme(axis.text.x = element_text(hjust=3))+
    theme(axis.text.y = element_text(vjust=2.5))

enter image description here

jpsmith
  • 11,023
  • 5
  • 15
  • 36
  • 7
    Does `sprintf` accomplish what you need? Check out [this answer](https://stackoverflow.com/a/5458799/10898875). – A. S. K. Nov 25 '19 at 20:13
  • Works like a charm - I replaced the `label` command with `label=sprintf("%.2f", round(k_median,2)))` and it solved the problem. Thank you! – jpsmith Nov 25 '19 at 21:34
  • Terrific; glad it worked! I'll vote to close this question since it ended up being similar to the other one. – A. S. K. Nov 25 '19 at 22:33

0 Answers0