如何根据 R 中的用户输入创建显示特定图的函数?

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

我有一组图,在这个例子中,为了简单起见,我将只使用以下内容:

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() 的函数,它在 show_plot(plot_name = "iris") 为 运行 时显示虹膜图,并在 show_plot(plot_name = "mpg) 为 [=23 时显示 mpg 图=].

我知道我会用以下内容开始我的功能:

show_plot <- function(plot_name){

}

但我真的不知道从这里继续下去。如果有人可以提供一些建议,那就太好了:)

您应该查看基本的 if-else 声明

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

您可以通过get获取函数内部的绘图对象,如下所示。

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

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

这还需要您在上游创建 mpg 和 iris 对象。

您可以使用此代码:

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

mpg 输出: