微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用自定义轴标题编写ggplot2函数

如何解决使用自定义轴标题编写ggplot2函数

我正在编写ggplot函数生成如下的多个图

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创建

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。