1

I have a collection of plots, in this example I'll just be using the following for simplicity:

library(tidyverse)
library(ggplot2)

iris <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point(size = 3)

mpg <- ggplot(mpg, aes(manufacturer, fill = manufacturer)) + geom_bar() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

I would like to create a function called show_plot() which disaplys the iris plot when show_plot(plot_name = "iris") is run and displays the mpg plot when show_plot(plot_name = "mpg) is run.

I know that I would start my function with the following:

show_plot <- function(plot_name){

}

But I really don't know where to go on from here. Would be great if someone could provide some suggestions :)

3 Answers 3

1

You should look into basic if-else statments

show_plot <- function(plot_name){
 
  if (plot_name == "iris") {
    
    gg <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
      geom_point(size = 3)
    
  } else if (plot_name == "mpg") {
    
    gg <- ggplot(mpg, aes(manufacturer, fill = manufacturer)) + geom_bar() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    
  } else {
    
    stop("Please select 'iris' or ' mpg'")
    
  }
  
  return(gg)
  
   
}

show_plot("iris")
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the plot object inside the function with get as follows.

# 1- Function
show_plot <- function(plot_name){
  return(get(plot_name))
}

# 2- Display the plot
show_plot(plot_name="iris")

This would also require that you have created upstream the mpg and iris objects.

Comments

0

You can use this code:

library(tidyverse)
library(ggplot2)

iris <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point(size = 3)

mpg <- ggplot(mpg, aes(manufacturer, fill = manufacturer)) + geom_bar() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

show_plot <- function(plot_name) {
  return(get(plot_name))
}

show_plot("mpg")

Output for mpg:

enter image description here

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.