creating a shortcut function for applying styling options

Morning all,
I'm trying to make a function that makes it easier to do two things I do on nearly every ggplot figure I make: Center the title and remove grid lines. My function is as follows:

style_ggplot=function(gg_graph, center_title, remove_gridlines){
    if(center_title==TRUE) (gg_graph=gg_graph + theme(plot.title = element_text(hjust = 0.5)))
    if(remove_gridlines==TRUE) (gg_graph=gg_graph + theme(panel.grid = element_blank()))
    return(gg_graph)
  }

It works if I apply it separately to a plot that already exists in the environment, for instance:

plot=ggplot(mtcars, aes(x=cyl, y=mpg))+ 
    geom_col()+
    labs(title = "test")
  
  style_ggplot(gg_graph =plot,  center_title = TRUE, remove_gridlines = FALSE)

However, it doesn't work when I include it as a line as a part of the creation of the plot. It gives me an error:

plot=ggplot(mtcars, aes(x=cyl, y=mpg))+ 
    geom_col()+
    labs(title = "test")+
    style_ggplot(gg_graph =.,  center_title = TRUE, remove_gridlines = FALSE)

Anyone know how to fix this? Or if it's possible to get it to work in this way?

1 Like

Have you tried using the pipe instead of +?

plot=ggplot(mtcars, aes(x=cyl, y=mpg))+ 
    geom_col()+
    labs(title = "test") %>%
    style_ggplot(gg_graph =.,  center_title = TRUE, remove_gridlines = FALSE)

I have. Unfortunately that doesn't work :frowning: it will create a plot, but it erases the title completely and doesn't remove the grid lines for some reason. Could be a problem with the way I wrote the function?

This topic was automatically closed 21 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.