0

I recently created some graphs in R ggplot, everything works fine except my code that is bit messy since that for each graph im using this styling

theme(
    axis.text.x = element_text(size = 8),
    axis.text.y = element_text(size = 8),
    axis.title.x = element_blank(),
    axis.title.y = element_text(size = 11),
    legend.position = "bottom",
    legend.title = element_blank(),
    legend.text = element_text(size=9),
    legend.spacing.x = unit(0.25, 'cm'),
    axis.text.y.right = element_text(hjust = 0),
    plot.title = element_text(size = 15, hjust = 0.5)
  ) 

Is it possible to recreate this piece of code as function that I can apply for each graph?

1
  • 2
    Assign it to mytheme and do p + mytheme? I don't know why you need a function. Commented Jul 23, 2019 at 8:56

2 Answers 2

0

I think that you can only use it as a theme() and paste it in every graph you want.

Sign up to request clarification or add additional context in comments.

3 Comments

well a thought the same but i can't
@ZcelaAnonymní What do you mean, you can't? Is it that you must make it into a function, or you don't want to use it as in theme ?
This is directly false; theme() always returns a list of its arguments, which can be appended to any ggplot2 or theme object.
0

You can simply do :

my_theme <- function(){
  theme(
    axis.text.x = element_text(size = 8),
    axis.text.y = element_text(size = 8),
    axis.title.x = element_blank(),
    axis.title.y = element_text(size = 11),
    legend.position = "bottom",
    legend.title = element_blank(),
    legend.text = element_text(size=9),
    legend.spacing.x = unit(0.25, 'cm'),
    axis.text.y.right = element_text(hjust = 0),
    plot.title = element_text(size = 15, hjust = 0.5)
  ) 
}

and then, given a plot p you just have to do

p + my_theme()

2 Comments

You don't even have to create it as a function. You can directly assign mytheme <- theme(...) and then add that to your ggplot2 plot.
Sure, but author is asking for a function, I'm giving a function.He may have some implicit reasons for wanting specificly a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.