问题描述
plotter <- function(data,x,y,z){ggplot(aes(y = {{x}},x = {{y}},fill = {{z}})) + geom_violin(draw_quantiles = c(0.25,0.5,0.75),scale = "count") +
scale_y_log10() + labs(y = "ylabel1",x = "xlabel1",title = "title1",caption = "Source: Authors' construction from the MIX data
*The red point is the mean. Horizontal lines show the first,second,and third quartiles
*The size of the violins is proportional to the data points") +
theme_economist() + theme(legend.position = "none") +
stat_summary(fun = mean,geom = "point",size = 1,color = "red")}
因为我想使用此函数生成许多图形,所以我希望能够为每个图形生成不同的x_labels,y-labels和标题。我该如何实现?
解决方法
您只需将它们作为参数添加到函数中即可
plotter <- function(data,x,y,z,xlabel,ylabel,title){
library(ggplot2)
ggplot(data = data,mapping = aes(y = {{x}},x = {{y}},fill = {{z}})) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75),scale = "count") +
scale_y_log10() +
labs(y = ylabel,x = xlabel,title = title,caption = paste0("Source: Authors' construction from the MIX data\n","*The red point is the mean. Horizontal lines show the ","first,second,and third quartiles\n","*The size of the violins is proportional ","to the data points")) +
ggthemes::theme_economist() +
theme(legend.position = "none") +
stat_summary(fun = mean,geom = "point",size = 1,color = "red")
}
现在让我们对一些虚拟数据进行尝试:
set.seed(69)
df <- data.frame(y = c(runif(100,1),runif(100,1,2),2,3)),x = runif(300),z = rep(LETTERS[1:3],each = 100))
plotter(df,"my x axis","my y axis","my title")
由reprex package(v0.3.0)于2020-09-01创建