PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

[FIXED] How to create a function which displays a specific plot depending on user input in R?

 June 27, 2022     function, ggplot2, graph, plot, r     No comments   

Issue

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


Solution

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


Answered By - mhesselbarth
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing