如何使用相同的数据遍历列并创建2个不同的图形

我对R有点陌生,并试图创建一个代码来帮助我遍历大型数据集,从而每列生成2个图形。为此,它必须考虑一些指定的变量并对其进行区分(请参见代码)。 在第一个图中,应该绘制一个箱线图/散点图,在这里我需要区分对照和患病人群。除此之外,我想看看有事件的人与没有事件的人之间的区别。

这实际上是有效的代码。现在,我要添加什么代码,以便将图形与变量的直方图结合起来,以便对数据的分布有一些了解。我试图将其添加到函数中,但是以某种方式不起作用

此外,我想将这两个图合并到一页中,并在整个循环中通过整个变量集将其保存为图像(请参见代码)

请在下面找到我到目前为止的代码。任何建议都非常感谢

library(ggplot2)
library(purrr)

创建一个具有随机数和2组的数据框

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)

使用一种新颜色为标签赋予特定的颜色(在1个图形中为组的颜色加上#号)

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)

按索引拉出名称 创建1个解释变量 用作解释值(第1列)

expl = names(df[1]) 

用于循环浏览2:5列

response = names(df[2:5]) 

使用命名向量

response = set_names(response)
response

expl = set_names(expl)
expl

散点图 功能的第一部分起作用 该功能的第1部分

scatter_fun = function(x,y) {
  ggplot(df,aes(x = .data[[x]],y = .data[[y]],color=color) ) + 
    geom_boxplot(fill="lightgrey",colour= "black",alpha=0.7,outlier.shape=NA) + 



geom_point(position = position_jitter(0.2)) +
    scale_color_manual(values= c("Control"="Orange","PAD with event" = "Red","PAD without event"="Green")) + # color the values as as you please
    labs(x = "",y = y,caption = "") +
    theme_bw() +
    theme(panel.grid.major = element_line(size = 0.1,linetype = 'solid',colour = "grey"),panel.grid.minor = element_line(size = 0.05,legend.title = element_blank(),legend.text = element_text(size=13),legend.key.size = unit(3,"line"))

该功能的PART 2(无效) 向函数添加直方图 这对我来说很复杂。我想从功能中得到3件事 1给我箱形图和散点图的上半部分 2我想在其中具有循环列的直方图(在这种情况下为b)的部分 了解价值的分布 3最后,我想将功能转换为一页,两列为PDF 遍历列时的文件 可以了解此情节的进展,可以使用下面的示例 举个例子 向功能添加直方图

ggplot(df,aes(x =.data[[x]])) +
    geom_histogram(fill="Orange",color="black",stat = "count")

}

仅指定列名时的工作方式示例

loopplots = map(expl,~scatter_fun(.x,"b") ) 
loopplots

运行此命令时,它会将控件和PAD分开,但是我不希望它们分开,而只是希望将两个组一起分配的总体思路

整个循环:当我运行此部分时,它仅保存函数的后半部分

event_vs_no_event = map(response,~map(expl,scatter_fun,y = .x) )

检查保存在b上的内容

event_vs_no_event$b

将所有图像保存为1个PDF->在这里,我想将直方图和对应于1列的散点图保存到1页中。

pdf("event_vs_no_event.pdf")
event_vs_no_event
dev.off() 

如何使用相同的数据遍历列并创建2个不同的图形

suzhuang 回答:如何使用相同的数据遍历列并创建2个不同的图形

我建议使用sth。以此为起点。与ggplot一起使用长数据帧比在ggplot中使用长数据帧更方便。在这里,我使用tidyr的gather来制作长数据帧。

library(tidyverse)
p1 <- df %>% 
  gather(response,value,-group,-event) %>% 
  ggplot(aes(group,color = event)) + 
   geom_boxplot(show.legend = F) + 
   geom_point(position = position_dodge(width = 0.8),show.legend = F) +  
   facet_wrap(~response,scales = "free_y")

p2 <- df %>% 
  gather(response,-event) %>% 
  ggplot(aes(value)) + 
  geom_histogram(fill="Orange",color="black",bins= 6) + 
  facet_wrap(~response,scales = "free") 

library(cowplot)

plot_grid(p1,p2,ncol = 1)

enter image description here

编辑

没有循环的最简洁的方法是s.th。像这样。

library(ggbeeswarm)
library(cowplot)
library(tidyverse)
plots <- df %>% 
  gather(response,-event) %>% 
  nest(-response) %>% 
  mutate(box_scatter = map2(data,response,~ggplot(.x,aes(group,value)) + 
        geom_boxplot(show.legend = F) + 
        geom_beeswarm(aes(color = event)) +
        ggtitle(.y))) %>% 
  mutate(hist = map(data,~ ggplot(.,aes(value)) + 
                      geom_histogram(fill="Orange",bins= 6)+
                      ggtitle("")))

pdf("all_plots.pdf",width = 15)
map2(plots$box_scatter,plots$hist,~plot_grid(.x,.y,ncol = 2,labels ="auto"))
dev.off()

当然,您也可以使用for循环

pdf("all_plots.pdf",width = 15)
for (i in names(df)[2:5]){
  p1 <- ggplot(df,aes_string("group",i)) + 
    geom_boxplot(show.legend = F) + 
    geom_beeswarm(aes(color = event))

  p2 <- ggplot(df,aes_string(i)) + 
    geom_histogram(fill="Orange",bins= 6)

  p_all <- plot_grid(p1,p2)
  print(p_all)
} 
dev.off()
本文链接:https://www.f2er.com/3124439.html

大家都在问