1

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.

2
  • So, you want the axes to show no labels at all? Commented Jun 28, 2019 at 9:23
  • Yes in this example. I am trying to create a family of 'look-functions' for ggplot to standardize looks. So one function will have arguments for names of the axis, and if the y-axis should show percents or not etc. Commented Jun 28, 2019 at 10:19

1 Answer 1

2

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()```
Sign up to request clarification or add additional context in comments.

1 Comment

wow, okay, I did not know you could use lists for this task. Thanks a lot for that tip. This solved my problem. Thank you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.