r - 在一个窗口r中为数据框中的每一列制作不同的图
问题描述
我为数据框中的每个变量制作了直方图、线图和箱线图,以评估每个变量的分布并将这些图绘制在一个窗口中。
对于变量,VARIABLE
我的代码如下所示:
variable_name_string = "VARIABLE"
hist = qplot(VARIABLE, data = full_data_noNO, geom="histogram",
fill=I("lightblue"))+
theme_light()
avg_price = full_data_noNO %>%
group_by(Month, Country) %>%
dplyr::summarize(avg = mean(VARIABLE, na.rm =
TRUE))
#line graph for different countries over time
line = ggplot(data=avg_price, aes(x=anydate(Month), y=VARIABLE,
group=Country)) +
xlab("Date")+
ylab(variable_name_string)+
geom_line(aes(color=Country), size = 1)+
theme_light()
#boxplot over different years
avg_price2 = avg_price
avg_price2$Month = format(as.Date(anydate(avg_price$Month), "%Y-%m-%d"),
"%Y")
box = ggplot(avg_price2, aes(x = Month, y=VARIABLE, fill = Month)) +
geom_boxplot()+
xlab("Date")+
ylab(variable_name_string)+
guides(fill=FALSE)+
theme_light()
var_name = grid.text(variable_name_string, gp=gpar(fontsize=20))
#merge plot into one window
grid.arrange(var_name, hist, line, box, ncol=2)
这适用于一个变量,但现在我想为我的数据框中的每个变量执行此操作,并为所有变量保存合并的绘图窗口。我一直在寻找几乎一整天,但我找不到解决方案。谁能帮我?
解决方案
如果没有可重现的示例,很难提供帮助,但您可以尝试将绘图代码包装在一个函数中,并用于lapply
为所有变量重复调用该函数。
make_plots <- function (variable_string) {
var_quo <- rlang::sym(variable_string)
hist = qplot(!!var_quo, data = full_data_noNO, geom="histogram",
fill=I("lightblue"))+
theme_light()
avg_price = full_data_noNO %>%
group_by(Month, Country) %>%
dplyr::summarize(avg = mean(!!var_quo, na.rm =
TRUE))
#line graph for different countries over time
line = ggplot(data=avg_price, aes(x=anydate(Month), y=!!var_quo,
group=Country)) +
xlab("Date")+
ylab(variable_string)+
geom_line(aes(color=Country), size = 1)+
theme_light()
#boxplot over different years
avg_price2 = avg_price
avg_price2$Month = format(as.Date(anydate(avg_price$Month), "%Y-%m-%d"),
"%Y")
box = ggplot(avg_price2, aes(x = Month, y=!!var_quo, fill = Month)) +
geom_boxplot()+
xlab("Date")+
ylab(variable_string)+
guides(fill=FALSE)+
theme_light()
var_name = grid.text(!!var_quo, gp=gpar(fontsize=20))
#merge plot into one window
combined <- grid.arrange(var_name, hist, line, box, ncol=2)
# Save combined plot at VARIABLE_plots.pdf
ggsave(paste0(variable_string, "_plots.pdf"), combined)
combined
}
# Make sure to pass the variable names as character vector
plots <- lapply(c("VARIABLE1", "VARIABLE2"), make_plots)
# OR
plots <- lapply(colnames(full_data_noNO), make_plots)
# Plots can also be accessed and printed individually
print(plots[["VARIABLE1"]])
推荐阅读
- laravel-7 - 试图获取非对象的属性“Product_image”(查看:F:\softwares\xampp\htdocs\MyProject\resources\views\home.blade.php)
- azure - 是否可以在没有任何登录信息的情况下使用 azureml?
- oracle-apex - Oracle APEX 将值设置为 Ajax 进程中的页面项
- wso2 - 为租户创建轴配置时出现 WSO2 APIUtil 错误
- python - 调用函数一定次数
- python - 在 python 中编辑 json 文件和请求库时出现问题
- kubernetes - 请参阅 Kubernetes 中的 Spec 模板变量以获取主机路径
- javascript - 如何从 From 外部更改 Formik TextField 值?
- sql - 在执行 SQL 插入语句时避免重复代码部分,该语句从一个表中获取数据,修改它,然后插入到另一个表中?
- c++ - 我已经将 MPI 代码从点到点转换为集体通信,我需要帮助来纠正代码中的一些值(矩阵向量乘法)