displaying too many decimal points in ggplot

Sorry, here comes a stupid question re: ggplot and rounding percentages. I’ve tried several ways of introducing the “round” function into both steps 2 and steps 3 below, but I can’t get rid of these unnecessary decimals. My goal is to round to either 1 decimal (51.9%) or perhaps just to 51% (depends on what looks best).

I have used the exact same code in other plots without having to use “round()” function so i’m confused why this problem suddenly appears here? (and why "round" doesn't seem to do the job)

Pasting reprex code below

  
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyverse)

# step 1  creat table with gropus and counts 
reason.3 <- tribble(
  ~typ, ~answer, ~count, 
  "industry", "yes", 903,
  "industry", "no",56, 
  "industry", "unsure", 46,
  "school/hosp.", "yes", 737,
  "school/hosp.", "no", 161, 
  "school/hosp.", "unsure", 107,
  "road", "yes", 831,
  "road",  "no", 108,
  "road",  "unsure", 66,
  "bike path",  "yes", 383,
  "bike path",  "no", 522,
  "bike path", "unsure", 100,
  "oil spill", "yes", 874, 
  "oil spill", "no", 56, 
  "oil spill", "unsure", 75, 
)

# step 2 calc  percents for graphing  
reason_pct <- reason.3 %>% 
  group_by(typ)  %>%  
  mutate(pct=prop.table(count)) 

reason_pct$typ <- fct_relevel(reason_pct$typ,   # re order levels low to higher
                              c("bike path", "school/hosp.", "road", "oil spill", "industry")) 

# step 3 graph
ggplot(reason_pct, 
       aes(x=typ, y=pct,fill=answer)) + 
  geom_col()+
  scale_fill_grey()+     # OBS i think this chagned for all m ohter graphs too !
  geom_text(aes(label = scales::percent(pct)),
            position="stack",vjust=+2.1,col="firebrick",size=3)+
  scale_y_continuous(label = scales::percent)

scales::pecent() accepts an accuracy argument. Try scales::percent(pct, accuracy = 1).

1 Like

Here are a few ways:

label = scales::percent(pct, accuracy=0.1) 
label = scales::percent(pct, accuracy=1) 

label = paste0(round(pct*100, 1), "%") 
label = paste0(round(pct*100), "%") 

label = sprintf("%1.1f%%", pct*100)
label = sprintf("%1.0f%%", pct*100)

Also, if you'd like the labels to be vertically centered, then replace position="stack",vjust=+2.1 with:

position=position_stack(vjust=0.5)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

thanks to @joels and @elmstedt. The following worked fine: "... accuracy=0.1".

and that was a bonus with the center adjust :slight_smile: thanks @joels