Home > OS >  How to create a function which displays a specific plot depending on user input in R?
How to create a function which displays a specific plot depending on user input in R?

Time:03-04

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 :)

CodePudding user response:

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")

CodePudding user response:

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.

CodePudding user response:

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

  • Related