John Karuitha
John Karuitha

Reputation: 369

Writing a ggplot2 function with custom axis titles

I am writing a ggplot function to generate several plots as follows

plotter <- function(data, x , y, z){ggplot(aes(y = {{x}}, x = {{y}}, 
  fill = {{z}})) + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75), scale = "count") + 
  scale_y_log10() + labs(y = "ylabel1", 
  x = "xlabel1", title = "title1", 
  caption = "Source: Authors' construction from the MIX data 
  *The red point is the mean. Horizontal lines show the first, second, and third quartiles
  *The size of the violins is proportional to the data points") + 
  theme_economist() + theme(legend.position = "none") + 
  stat_summary(fun = mean, geom = "point", size = 1, color = "red")}

Because I want to use this function to generate many graphs, I want a capability to generate different x_labels, y-labels and title for each graph. How can I achieve this?

Upvotes: 1

Views: 66

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174516

You can simply add them as parameters to your function:

plotter <- function(data, x , y, z, xlabel, ylabel, title){
  library(ggplot2)
  ggplot(data = data, 
         mapping = aes(y = {{x}}, x = {{y}}, fill = {{z}})) + 
  geom_violin(draw_quantiles = c(0.25, 0.5, 0.75), scale = "count") + 
  scale_y_log10() + 
  labs(y = ylabel, x = xlabel, title = title, 
  caption = paste0("Source: Authors' construction from the MIX data\n",
                   "*The red point is the mean. Horizontal lines show the ",
                   "first, second, and third quartiles\n",
                   "*The size of the violins is proportional ",
                   "to the data points")) + 
  ggthemes::theme_economist() + 
  theme(legend.position = "none") + 
  stat_summary(fun = mean, geom = "point", size = 1, color = "red")
}

Now let's try it on some dummy data:

set.seed(69)

df <- data.frame(y = c(runif(100, 0, 1), runif(100, 1, 2), runif(100, 2, 3)),
                 x = runif(300),
                 z = rep(LETTERS[1:3], each = 100))

plotter(df, x, y, z, "my x axis", "my y axis", "my title")

Created on 2020-09-01 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions