Helgi Guðmundsson
Helgi Guðmundsson

Reputation: 846

Create user function for ggplot

I am trying to create a function to edit the look of a ggplot.

Here is a example of what I would like to create with a function (obviously the function I am trying to create is more complex, but this is for demonstration).

library(ggplot2)
library(dplyr)
group_by(iris, Species) %>%
  summarise(m = mean(Sepal.Width)) %>%
  ggplot(aes(x = Species, y = m)) +
  geom_col() + 
  xlab("") + ylab("")

Here is the function I am trying to make:

name_axis <- function(){
  xlab(label = "") + 
  ylab(label = "")   
}

group_by(iris, Species) %>%
  summarise(m = mean(Sepal.Width)) %>%
  ggplot(aes(x = Species, y = m)) +
  geom_col() + 
  name_axis()

I know I could just do this by first save the plot to a object and then pass the plot to the new function. But I want to skip that step and use the "+" instead.

Upvotes: 1

Views: 89

Answers (1)

Carles
Carles

Reputation: 2829

You can do that with

  1. a list():
    name_axis <- list(
      xlab(label = "Nothing"),  
      ylab(label = ""))

    group_by(iris, Species) %>%
      summarise(m = mean(Sepal.Width)) %>%
      ggplot(aes(x = Species, y = m)) +
      geom_col() + 
      name_axis
  1. passing a list inside the function:
  name_axis <- function(){
      list(xlab(label = ""), 
        ylab(label = "hello"))   
    }

   group_by(iris, Species) %>%
      summarise(m = mean(Sepal.Width)) %>%
      ggplot(aes(x = Species, y = m)) +
      geom_col() + 
      name_axis()```

Upvotes: 2

Related Questions