Chris A.
Chris A.

Reputation: 435

Creating a function with ggplot in body and producing two plot outputs per call

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.

Upvotes: 0

Views: 48

Answers (1)

yake84
yake84

Reputation: 3236

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

Upvotes: 1

Related Questions