我是菜鸟,所以希望这有意义...
问题/问题陈述
我需要创建多个图,其中每个图的唯一区别是所使用的组-每个组都包含分类变量。我可以通过手动键入所有代码来完成此工作。
我希望开发一个循环来自动执行此绘制过程,而不是将每个组手动写入R。
当前的手动方法
这可行,但很乏味,我想通过一个循环实现自动化-这只是我9个小组中2个小组的例子。
唯一改变的是因素和标题
# GOR
ggplot(aes(y = dailyCV, x = factor(GOR)), data = mergedbed) +
geom_jitter(alpha=1/2, color="tomato", position=position_jitter(width=.2), size=1/10) +
stat_summary(fun.data = min.mean.sd.max, geom = "boxplot", alpha = 0.5) +
stat_summary(fun.y=mean, colour="black", geom="text",
vjust=0.5, hjust=1.5, size=3, aes( label=round(..y.., digits=1))) +
stat_summary(fun.data = give.n, geom = "text", vjust=1, hjust=-2, size=3) +
coord_flip() +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=2) +
xlab("GOR")+
ylab("Co-efficient of variation (%)")+
ggtitle("GOR vs dailyCV")
# ACCOM_EHCS
ggplot(aes(y = dailyCV, x = factor(ACCOM_EHCS)), data = mergedbed) +
geom_jitter(alpha=1/2, color="tomato", position=position_jitter(width=.2), size=1/10) +
stat_summary(fun.data = min.mean.sd.max, geom = "boxplot", alpha = 0.5) +
stat_summary(fun.y=mean, colour="black", geom="text",
vjust=0.5, hjust=1.5, size=3, aes( label=round(..y.., digits=1))) +
stat_summary(fun.data = give.n, geom = "text", vjust=1, hjust=-2, size=3) +
coord_flip() +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=2) +
xlab("ACCOM_EHCS")+
ylab("Co-efficient of variation (%)")+
ggtitle("ACCOM_EHCS vs dailyCV")
我的尝试
我在这里的尝试是用每个组创建一个向量,然后尝试循环执行此操作,但是它不起作用,我确定这是非常错误的。我第一次尝试创建循环。
myvariables <- c("GOR","ACCOM_EHCS","DBL_GLAZ", "BUILDING_AGE", "HhdSize", "Inc_Group_7s", "Person_Under_5", "Person_Over_64", "thermal")
lapply(myvariables, function(cc){
p <- ggplot(aes(y = dailyCV, x = factor(aes_string(y = cc))), data = mergedbed) +
geom_jitter(alpha=1/2, color="tomato", position=position_jitter(width=.2), size=1/10) +
stat_summary(fun.data = min.mean.sd.max, geom = "boxplot", alpha = 0.5) +
stat_summary(fun.y=mean, colour="black", geom="text",
vjust=0.5, hjust=1.5, size=3, aes( label=round(..y.., digits=1))) +
stat_summary(fun.data = give.n, geom = "text", vjust=1, hjust=-2, size=3) +
coord_flip() +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=2) +
xlab("???")+
ylab("Co-efficient of variation (%)")+
ggtitle("??? vs dailyCV")
p
})
提前谢谢
答案 0 :(得分:0)
以下是使用虹膜数据集和purrr的示例:
library(tidyverse)
data(iris)
## create a grid with variable combinations
variables <- iris %>%
select(everything(), -Species) %>%
names() %>%
expand.grid(x = ., y =., stringsAsFactors = F)
##create plotting function
plot_data <- function(data, x, y){
ggplot(data, aes_string(x, y)) +
geom_point() +
ggtitle(paste(x, "vs", y))
}
map2(.x = variables$x,
.y = variables$y,
.f = ~ plot_data(iris, .x, .y))
这将创建图的所有变量组合并更改标题。