[Solved] Theme for ggplot2 in r


First define a function with the elements that need to be changed as arguments. Set those arguments to defaults in the graph you really like. To change the defaults, pass them on to the function in its calls.

library(ggplot2)

my_theme <- function(plot_title_size = 30, colour = "black", size = 20, angle= 0){
  theme(plot.title = element_text(family ="serif", 
                                  face = "bold",
                                  colour = colour,
                                  size = plot_title_size),
        axis.title.x = element_text(family = "serif", 
                                    colour = colour, 
                                    size = size),
        axis.title.y = element_text(family = "serif",
                                    colour = colour, 
                                    size = size),
        axis.text.x = element_text(size = 10, angle = angle, vjust = 0.5)) 
}


ggplot(subset(diamonds, color == "E"), aes(carat, price)) +
  geom_point(size = 2) +
  scale_y_continuous("Price ($)") +
  scale_x_continuous("Carat") +
  ggtitle("Colourless E Diamonds") +
  geom_smooth(formula = y ~ x,method=lm,se=FALSE) +
  my_theme()

ggplot(subset(diamonds, color == "E"), aes(carat, price)) +
  geom_point(size = 2) +
  scale_y_continuous("Price ($)") +
  scale_x_continuous("Carat") +
  ggtitle("Colourless E Diamonds") +
  geom_smooth(formula = y ~ x,method=lm,se=FALSE) +
  my_theme(colour = "grey30", angle = 45)

Created on 2022-03-28 by the reprex package (v2.0.1)

solved Theme for ggplot2 in r