例如,來自
使用下面的代碼,我分別創建了 3 個樣本p1,setp2和p3's 引數:df1df2df3
set.seed(1)
df1 <- slice_sample(iris, n = 10)
df2 <- slice_sample(iris, n = 10)
df3 <- slice_sample(iris, n = 10)
# to set df1's and arguments (seems not good enough to store parameters, maybe I need to save it as config or ymal file?)
df1_plot1_param <- c(df='df1', x='Petal.Width', y='Sepal.Width', col='Species')
df1_plot2_param <- c(df='df1', x='Petal.Length', y='Sepal.Width', fill='Species')
df1_plot3_param <- c(df='df1', x='Sepal.Width', y='Petal.Width', col='Species')
# to set df2's arguments
df2_plot1_param <- c(df='df2', x='Sepal.Length', y='Sepal.Width', col='Species')
df2_plot2_param <- c(df='df2', x='Petal.Length', y='Sepal.Width', fill='Species')
df2_plot3_param <- c(df='df2', x='Sepal.Length', y='Petal.Width', col='Species')
# to set df3's arguments
df3_plot1_param <- c(df='df3', x='Sepal.Length', y='Sepal.Width', col='Species')
df3_plot2_param <- c(df='df3', x='Petal.Length', y='Sepal.Width', fill='Species')
df3_plot3_param <- c(df='df3', x='Sepal.Length', y='Petal.Width', col='Species')
for i in c(df1's params, df2's params, df3's params):
purrr:map(plot_func(df{i}_param))
最終結果將是 3 個df帶有預定義引數的 s 繪圖。
但是我不知道如何使整個代碼運行起來,提前感謝您的幫助,非常感謝。
參考鏈接:
使用 dplyr 創建多個 ggplots
uj5u.com熱心網友回復:
嘗試這樣的事情。您可以在函式中指定 X/Y 和分組等。
編輯:根據問題添加資料框作為函式的引數
set.seed(1)
df1 <- slice_sample(iris, n = 10)
library(ggplot2)
library(patchwork)
my_plot = function(DF=df, X="", Y="", GROUP=""){
# Create ggplot2 scatterplot
p1 <- ggplot(DF,
aes(x = .data[[X]],
y = .data[[Y]],
col = Species))
geom_point()
p1
# Create ggplot2 barchart
p2 <- ggplot(DF,
aes(x = .data[[GROUP]],
y = .data[[Y]],
fill = .data[[GROUP]]))
geom_bar(stat = "identity")
p2
# Create ggplot2 boxplot
p3 <- ggplot(DF,
aes(x = .data[[GROUP]],
y = .data[[Y]],
col = .data[[GROUP]]))
geom_boxplot()
p3
# Create plot composition
p <- (p1 p2) / p3
# Draw plot composition
return(p)
}
test = my_plot(DF=iris, X= "Sepal.Length",Y = "Sepal.Width", GROUP="Species")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416789.html
標籤:
