0

I am trying to create a function that contains ggplot in the function body, and yields two or more plots per call.

I have taken the approach of initially testing my function with only one plot being produced, and it has worked. I have called my plots outside of the function to ensure I am coding them correctly, and they work on an individual basis. The following code only produces a single barplot with the y axis scaled to 1, with no error:

library(tidyverse)

cat_plots <- function(dat, var1, var2){

  nums <- ggplot(dat) + geom_bar(aes_string(var1, fill = var2)) 

  props <- ggplot(dat) + 
    geom_bar(aes_string(var1, fill = var2), position = "fill")

  nums
  props
}

cat_plots(diamonds, "cut", "clarity")

The expected result is a plot for nums and a plot for props - I am trying to simultaneously produce two plots, with raw counts and with proportions, in order to easily compare between the two. I don't get an error returned. I only get the last barplot, showing only proportions. The expected barplot with counts in the y axis does not appear at all.

1
  • 5
    R functions are only allowed to return 1 object. If you want to return multiple objects, put them in a list, list(nums, props). If you want to display both plots (I'd recommend giving the user an option to disable this), explicitly print() them in the function. print(nums); print(props). Commented Jun 6, 2019 at 19:01

1 Answer 1

1

Would a solution like this work for you? grid.arrange() is an easy way to print out two plots at once.

library(tidyverse)

cat_plots <- function(dat, var1, var2){

  nums <- ggplot(dat) + geom_bar(aes_string(var1, fill = var2)) 

  props <- ggplot(dat) + 
    geom_bar(aes_string(var1, fill = var2), position = "fill")

  gridExtra::grid.arrange(nums, props, ncol = 1)
}

cat_plots(diamonds, "cut", "clarity")

enter image description here

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

Comments

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.