我有一組圖,在這個例子中,為了簡單起見,我將使用以下內容:
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")運行時顯示 mpg 圖show_plot(plot_name = "mpg)。
我知道我會從以下內容開始我的功能:
show_plot <- function(plot_name){
}
但我真的不知道從這里開始。如果有人可以提供一些建議會很棒:)
uj5u.com熱心網友回復:
您應該查看基本的 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")
uj5u.com熱心網友回復:
您可以使用以下方法獲取函式內部的繪圖物件get。
# 1- Function
show_plot <- function(plot_name){
return(get(plot_name))
}
# 2- Display the plot
show_plot(plot_name="iris")
這還需要您在上游創建 mpg 和 iris 物件。
uj5u.com熱心網友回復:
您可以使用以下代碼:
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 的輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/438319.html
