Home > front end >  Trying to add commas to data labels in ggplots geom_text()
Trying to add commas to data labels in ggplots geom_text()

Time:12-31

I have created a waterfall chart using R in Power BI. I am trying to add commas to the data labels that I have on my bars. So, one of my bars has a value of 1326, I want it to display as 1,326. The issue seems to be that I also need to remove the decimals on the number as well. Is there a way to both remove the decimals and add in a comma?

Here is what I have for code:

 ggplot(dataset, aes(x = Recon_cat,  fill = Increase_or_Decrease_TP )) 
    geom_rect(aes(x =Recon_cat,
     xmin = id - 0.2 ,
      xmax = id   0.2,  
      ymin = end, 
      ymax = start ),
      alpha=0.95)  

   
   geom_text(x= dataset$Recon_cat, y= dataset$end,  size = 11 / .pt, vjust = "top",label = sprintf("%0.0f", round(dataset$Value, digits = 6)))  
    scale_y_continuous(labels = label_comma()) 
    scale_x_discrete(labels = function(Recon_cat) str_wrap(as.character(Recon_cat), width = 8))  
    scale_fill_manual(values = c("Net_PD" = "#54585A", "Net_PUD" = "#A0A0A0", "Decrease" = "#F68D2E", "Increase" = "#0075BC" )) 
    theme(legend.position = "none",axis.title.x=element_blank(),panel.background = element_rect(fill = "white", colour = "white",
                                size = .25, linetype = "solid"),
  panel.grid.major = element_line(size = 0.25, linetype = 'solid',
                                colour = "white"), 
  panel.grid.minor = element_line(size = 0.25, linetype = 'dashed',
                                colour = "white"), axis.line = element_line(colour = "black"))  
                                labs( tag = "MMBOE")

Data set looks like enter image description here

I have tried adding in this to aes in the geom_text section, but it doesnt seem to do anything:

aes(label = format(dataset$Value, big.mark = ',' , scientific = FALSE) )

CodePudding user response:

Got it figured out, replaced label = sprintf("%0.0f", round(dataset$Value, digits = 0))

with

label = format(round(dataset$Value, digits = 0),big.mark=",",scientific=FALSE)

  • Related