rggplot2sjplot

How to tweak geom_text element in sjPlot


I use this code:

library(sjPlot)

mtcars |> 
  plot_frq(cyl)

and I get enter image description here

I would like to remove the parentheses and round the percentage numbers to the nearest whole number. So that I get 34% instead of (34.4%). I am looking for a direct way to access the ggplot elements.

I tried accessing the underlying ggplot object but was unsuccessful.

Thank you very much!


Solution

  • I agree with @qdread that it might be easier to build the plot from scratch. But if you want to do the hacky approach then one option would be to get rid of the labels added by plot_frq and add your own:

    library(sjPlot)
    library(ggplot2)
    
    p <- mtcars |>
      plot_frq(cyl)
    
    p$layers[[2]]$aes_params$label <- NULL
    
    p +
      aes(label = paste(
        .data$frq,
        scales::percent(.data$frq / sum(.data$frq), accuracy = 1),
        sep = "\n"
      ))