簡體   English   中英

循環遍歷數據框列以使用 ggplot2 創建繪圖

[英]Looping over columns of data frame to create plots with ggplot2

我正在努力克服這一點。 不能再進一步了。

我有一個包含因子和數字變量的數據框。 這里顯示的是前幾行和幾列。

# A tibble: 6 x 5
  cluster SEV_D SEV_M   OBS   PAN  
    <int> <dbl> <dbl> <fct> <fct>  
1       1     5     1    0     1    
2       2     6     1    0     0    
3       1     5     1    0     1    
4       2     4     2    0     0    
5       1     4     1    1     1    
6       1     4     2    1     0   

cluster=as.factor(c(1,2,1,2,1,1))  
SEV_D=as.numeric(c(5,6,5,4,4,4))
SEV_M=as.numeric(c(1,1,1,2,1,2))
OBS=as.factor(c(0,0,0,0,1,1))
PAN=as.factor(c(1,0,1,0,1,0))
data<-data.frame(cluster,SEV_D,SEV_M,OBS,PAN) 

我像這樣在數字和因子變量中拆分數據框,在兩個子集中保留“集群”,因為我需要它進行分組。

data_fact <- data[, sapply(data, class) == 'factor']

data_cont <- data[, sapply(data, class) == 'numeric' | names(data) 
== "cluster"]

以下兩個代碼片段將生成我想要的圖。

data_fact %>% group_by(cluster,OBS)%>%summarise(total.count=n()) %>% 
ggplot(., aes(x=cluster, y=total.count, fill=OBS)) + 
geom_bar(position = 'dodge', stat='identity') + 
geom_text(aes(label=total.count),  
position=position_dodge(width=0.9), vjust=-0.2)

data_cont %>% group_by(cluster) %>% dplyr::summarise(mean = 
mean(SEV_D), sd = sd(SEV_D)) %>% 
ggplot(.,aes(x=cluster,y=mean))+geom_bar(position=position_dodge(), 
stat="identity",colour="black",size=.3)+geom_errorbar(aes(ymin=mean- 
sd, ymax=mean+sd),size=.3,width=.4,position=position_dodge(.4)) + 
ggtitle("SEV_D")

我的目標是在數據框中創建與變量一樣多的圖形,循環列並將這些圖形存儲在一張紙中。

我的嘗試是

col<-names(data_fact)[!names(data_fact)%in%"cluster"]

for(i in col) {
data_fact %>% group_by(cluster,i)%>%summarise(total.count=n()) %>% 
ggplot(., aes(x=cluster, y=total.count, fill=i)) + geom_bar(position 
= 'dodge', stat='identity') + geom_text(aes(label=total.count), 
position=position_dodge(width=0.9), vjust=-0.2)
}

但它拋出這個錯誤:

grouped_df_impl(data, unname(vars), drop) 中的錯誤:第i列未知

最重要的是,我擔心該代碼不會在一張紙中顯示所有圖形。 任何幫助將非常感激!!!

上面的鏈接是一個很好的參考。 或者查看 Rstudio 的 tidyeval 備忘單: https : //github.com/rstudio/cheatsheets/raw/master/tidyeval.pdf

要在 ggplot 語句中計算i ,您需要使用!!ensym( )函數構造!!ensym( )對字符串的!!ensym( ) 此外,您將需要使用print語句打印循環內的圖。

library(ggplot2)

col<-names(data_fact)[!names(data_fact)%in%"cluster"]

for(i in col) {
   print(i)

   g<-data_fact %>% group_by(cluster, !!ensym(i)) %>% summarise(total.count=n()) %>% 
     ggplot(., aes(x=cluster, y=total.count, fill=!!ensym(i))) + 
     geom_bar(position  = 'dodge', stat='identity') + 
     geom_text(aes(label=total.count), position = position_dodge(width=0.9), vjust=-0.2) +
     labs(title=i)
  print(g)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM