我正在嘗試ggplot在自定義函式中使用,例如
Ploy <- function(Sepal.Length = Sepal.Length, Sepal.Width = Sepal.Width,
Petal.Width = Petal.Width){
#Calculate some derived parameters
deltak <- (Sepal.Length - Sepal.Width)/390
ARk <- Petal.Width*2
dat <- cbind.data.frame(deltak, ARk)
#Fitting quadratic model
mod <- lm(deltak ~ poly(ARk, 2, raw = TRUE))
dat$pred = predict(mod, newdata = dat)
#Plotting using ggplot2
require(ggplot2)
myplot <- function(mydf, xcol, ycol){
ggplot2::ggplot(data = mydf, aes(x = {{xcol}}, y = {{ycol}}))
ggplot2::geom_point(color='red', alpha=0.3, size=3)
ggplot2::stat_smooth(method='lm', formula = y~poly(x,2), se = F)
ggplot2::theme_bw()
ggplot2::xlab("X-axis")
ggplot2::ylab("Y-axis")
ggplot2::theme(panel.grid = element_blank())}
myplot(dat, ARk, deltak)
deltaK0 <- abs(mod$coefficients[[1]])
return(c(`DeltaK0` = deltaK0))
}
當我將函式呼叫為
Ploy(Sepal.Length = iris$Sepal.Length, Sepal.Width = iris$Sepal.Width,
Petal.Width = iris$Petal.Width)
它沒有回傳我的情節。如何將繪圖作為函式的輸出?如何data在函式中使用引數?
uj5u.com熱心網友回復:
您必須顯式回傳繪圖物件。保持你的語法:
[...]
my_plot <- myplot(dat, ARk, deltak)
deltaK0 <- abs(mod$coefficients[[1]])
return(
list(
'DeltaK0' = deltaK0,
'Plot' = my_plot
)
)
}
然后呼叫函式并繪制
output <- Ploy(...)
output$Plot
output$deltaK0
uj5u.com熱心網友回復:
這應該為您解決問題(根據@SEcker的回答)
Ploy <- function(Sepal.Length = Sepal.Length, Sepal.Width = Sepal.Width,
Petal.Width = Petal.Width){
#Calculate some derived parameters
deltak <- (Sepal.Length - Sepal.Width)/390
ARk <- Petal.Width*2
dat <- cbind.data.frame(deltak, ARk)
#Fitting quadratic model
mod <- lm(deltak ~ poly(ARk, 2, raw = TRUE))
dat$pred = predict(mod, newdata = dat)
#Plotting using ggplot2
require(ggplot2)
myplot <- function(mydf, xcol, ycol){
ggplot2::ggplot(data = mydf, aes(x = {{xcol}}, y = {{ycol}}))
ggplot2::geom_point(color='red', alpha=0.3, size=3)
ggplot2::stat_smooth(method='lm', formula = y~poly(x,2), se = F)
ggplot2::theme_bw()
ggplot2::xlab("X-axis")
ggplot2::ylab("Y-axis")
ggplot2::theme(panel.grid = element_blank())}
my_plot = myplot(dat, ARk, deltak)
deltaK0 <- abs(mod$coefficients[[1]])
my_list = list(
'DeltaK0' = deltaK0,
'Plot' = my_plot
)
return(my_list)
}
output = Ploy(Sepal.Length = iris$Sepal.Length, Sepal.Width = iris$Sepal.Width,
Petal.Width = iris$Petal.Width)
output$Plot`
舊代碼
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()
return(p1)
}
plot_stuff = my_plot(DF=iris, X= "Sepal.Length",Y = "Sepal.Width", GROUP="Species")
plot_stuff
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416785.html
標籤:
上一篇:R中{ggpval}包的問題
