在R studio中通过函数调用制作多个图

我对R相对较新。我的问题来自在线学习课程中的一个项目。我正在使用R studio从一个函数调用中绘制多个图。我想要为每列表示y轴的新图,而x轴保持等于月份。显示单个变量时,该功能有效。但是,当我尝试使用多列进行函数调用时,会收到:

“错误:解析了多个表达式”

类似的代码在在线程序的模拟平台中起作用。

我在下面的代码中提供了数据框中的一小部分示例。是否可以通过这种方式导出多个图?如果是这样,我该如何更新或更正我的代码以绘制每一列的图。

month <- c('mar','oct','oct')
day <- c('fri','tue','sat')
FFMC <- c(86.2,90.6,90.6)
DMC <- c(26.2,35.4,43.7)
DC <- c(94.3,669.1,686.9)
ISI <- c(5.1,6.7,6.7)
temp <- c(8.2,18.0,14.6)
RH <- c(51,33,33)
wind <- c(6.7,0.9,1.3)
rain <- c(0.0,0.0,0.0)

forestfires_df <- data.frame(month,day,FFMC,DMC,DC,ISI,temp,RH,wind,rain)

library(ggplot2)
library(purrr)

month_box <- function(x,y) {
  ggplot(data = forestfires_df,aes_string(x = month,y = y_var)) + 
    geom_boxplot() +
    theme_bw()
}

month <- names(forestfires_df)[1]
y_var <- names(forestfires_df)[3:10]

month_plots <- map2(month,y_var,month_box) 

#After running month_plots I receive "Error: More than one expression parsed"
drx321 回答:在R studio中通过函数调用制作多个图

问题在于函数参数应该与内部参数匹配

month_box <- function(x,y) {
   ggplot(data = forestfires_df,aes_string(x = x,y = y)) + 
   geom_boxplot() +
   theme_bw()
 }

如果我们使用'month'和'y_var',则'y_var'的长度为8,这就是我们在map中进行循环的原因。进行更改后,map2应该会按预期工作

map2(month,y_var,month_box) 

或使用匿名功能

map2(month,~ month_box(.x,.y))
,

就像我在评论中提到的那样,aes_string已被弃用,而赞成using tidyeval to write ggplot2 functions。您可以将函数重写为一个简单的基于tidyeval的函数,然后像大多数其他tidyverse函数一样,通过裸列名称或位置映射感兴趣的列。

有两种方法可以编写这样的函数。较旧的方法是使用quosures和unquoting列,但其语法可能会造成混淆。 dplyr带有非常深入的插图,但是我喜欢this blog post作为快速指南。

month_box_quo <- function(x,y) {
  x_var <- enquo(x)
  y_var <- enquo(y)
  ggplot(forestfires_df,aes(x = !!x_var,y = !!y_var)) +
    geom_boxplot()
}

单个调用如下所示,列名称为裸露

month_box_quo(x = month,y = DMC)

或使用map_at和列位置(或使用vars()):

# mapped over variables of interest; assumes y gets the mapped-over column
map_at(forestfires_df,3:10,month_box_quo,x = month)
# or with formula shorthand
map_at(forestfires_df,~month_box_quo(x = month,y = .))

newer tidyeval syntax{{}}或卷曲卷曲)更容易理解,并返回与上述相同的图列表。

month_box_curly <- function(x,y) {
  ggplot(forestfires_df,aes(x = {{ x }},y = {{ y }})) +
    geom_boxplot()
}
本文链接:https://www.f2er.com/3093461.html

大家都在问