我制作了一个循环,每个变量输出1个固定变量(控制与PAD)的2个图形。使用plot_grid函数,我做了2行(标题为1行),虽然不是很直观,但是行得通(如图所示),但是现在我想为两个组添加代表均值和SD的值(最好是在图例)我为均值和标准差做了一个向量,但是在将它们添加到最终绘图中时我有点迷失了。也许还有一种更简便的方法。
我在下面做了一个示例代码。我还附上一张描述我喜欢它的图片。
创建数据框
rm(list=ls())
library(ggplot2)
library(purrr)
library(ggbeeswarm)
library(cowplot)
library(plotly)
library(dplyr)
library(tidyr)
library(plyr)
group <- c("Control","PAD","Control","PAD")
b <- round(runif(15,1,7))
c <- round(runif(15,3))
d <- round(runif(15,3,8))
e <- round(runif(15,5))
event <- c("no event","event","no event","event")
df <- data.frame(group,b,c,d,e,event)
df
rm(group,event)
将颜色定义为箱线图使用的组
df$color <- "color"
for (i in 1:dim(df)[1]){
if (df$group[i]=="Control") {
df$color[i] <- "Control" # in de column PAD,if the control is control give the color the string "control"
}
}
for (i in 1:dim(df)[1]){
if (df$group[i] == "PAD" && df$event[i] == "event") {
df$color[i] <- "PAD with event" # in de column PAD,if the PAD has event give the color the string "event"
}
}
for (i in 1:dim(df)[1]){
if (df$group[i] == "PAD" && df$event[i] == "no event") {
df$color[i] <- "PAD without event"
}
}
rm(i)
用于循环浏览列
expl = names(df[1])
response = names(df[2:5])
response = set_names(response)
response
expl = set_names(expl)
expl
图2中使用的子集PAD和控件获取平均值和sd
PADonly <- subset(df,group == "PAD" )
Ctrlonly <- subset(df,group == "Control" )
explPAD = names(df[7]) #the explanatory value is event vs no event)
response = names(DBPAD[2:5])
运行循环
pdf("all_plots.pdf",width = 15)
xPAD <- PADonly[,i]
xPADmean <- mean(xPAD,na.rm=TRUE)
xPADSD <- sd(xPAD,na.rm = TRUE)
xctrl <- Ctrlonly[,i]
xctrlmean <- mean(xctrl,na.rm=TRUE)
xctrlSD <- sd(xctrl,na.rm = TRUE)
p1 <- ggplot(df,aes_string("group",i)) +
geom_boxplot(show.legend = F) +
geom_beeswarm(aes(color = color),size=2) +
scale_color_manual(values= c("Control"="#107f40","PAD with event" = "#D85622","PAD without event"="#2D416D")) # color the values as as you please
p2 <- ggplot(df,aes_string(x= i,fill="group")) +
geom_histogram(bins=15,aes(y=..density..),position = "identity",alpha=0.15,color="black") +
scale_fill_manual(values= c("PAD"="#2D416D","Control" = "#D85622")) + # color the values as as you please
scale_y_continuous(labels = scales::percent) +
stat_density(aes_string(i,color="group"),na.rm=TRUE,bw = "nrd0",geom = "line",size=1,linetype=2) +
geom_rug(aes_string(x=i,color="group")) +
scale_color_manual(values= c("PAD"="#2D416D","Control" = "#D85622"))+
geom_vline(xintercept=xPADmean,linetype=2,color="#2D416D")+
geom_vline(xintercept=xctrlmean,color="#D85622")
p_all <- plot_grid(p1,p2)
# create a title vector for i
title <- ggdraw() +
draw_label(i,fontface = "bold",x = 0,hjust = 0,size = 25) +
theme(
# add margin on the left of the drawing canvas
plot.margin = margin(0,7,))
p_all <- plot_grid(title,p_all,ncol=1,rel_heights = c(0.1,1))
print(p_all)
}