Search code examples
rggplot2geom-text

How to set different digit rounding specifications for labels with geom_text?


I am attempting to label my bar graph with data rounded to one decimal point. However, I have values that are 0. I'd like to find someway to make sure that the zero values are not being displayed as 0.0. I would like them to be displayed as 0.

Here is what my plot looks like currently: enter image description here

Code: p2+geom_text(aes(label=sprintf("%0.1f", pct)), position=position_dodge(width=0.7), vjust=-0.25, size=3)

I approached this by attempting to not label the 0 values at all. However, this created a problem where my labels were not aligned properly. (note the label offset for 0. for Native American in the furthest left panel).

enter image description here

Code: p2+geom_text(data=subset(demo_long_pct,pct != 0),aes(label=sprintf("%0.1f", pct)), position=position_dodge(width=0.7), vjust=-0.25, size=3)


Solution

  • How about using an ifelse statement in there. Something like this..

    p2 + geom_text(aes(label=ifelse(test = pct == 0, yes = pct, no = sprintf("%0.1f", pct)), position=position_dodge(width=0.7), vjust=-0.25, size=3) 
    

    You could also replace the yes conditional argument with 0 if it still labelled with decimal points.