2017-08-08 122 views
1

我想爲數據集的每一列創建一個圖形(使用quickplot)並將其保存到一個文件夾作爲PDF - 任何建議將不勝感激!如何使用ggplot自動在R中繪製圖形並將它們保存到文件夾?

到目前爲止,我已經做了一個試驗數據幀(之前,我嘗試用500+列)

test.data <-cbind.data.frame(data$col_1,data$col_2,data$col_3) 

然後我試圖寫一個函數來繪製並保存圖表。我試圖製作圖表條形圖(有些標題爲&顏色規格),它們顯示了編號的數量。每個類別的人。所以這些列通常由分類數據組成。

plot.graphs <- function(x) {  
    for(i in colSums(x)){ 
    plots <- quickplot(i) + 
     geom_bar(color= "#6267c1", fill="#6267c1") + 
     labs(title= "i", 
      x="i", 
      y="Count") + 
     theme(help() 
     plot.title = element_text(colour = "#453694"), 
     axis.title = element_text(colour ="#453694")) 
    ggsave(plots,filename = "testplot",nm[1],".pdf",sep="") 
    print(plots) 
    } 
} 
plot.graphs(test.data) 

但是,這似乎出現了很多錯誤,所以我認爲我沒有把它做對。

+1

'for(colSums()''colSums'是一個函數,其中'for'的右括號在哪裏?函數裏面使用了'i'?另一個問題可能是你r輸入數據是'matrix'(使用'cbind')而不是'data.frame',即'test.data < - data [c(「col_1」,「col_2」,「col_3」)]' – akrun

+1

非常感謝,我會嘗試進行這些更改! – datastudent

回答

0

嘗試用pdf()圖形設備和dev.off()包裝您的劇情代碼。 pdf()將打開一個pdf圖形設備,並將您生成的所有圖形存儲在一個文件中,直到您使用dev.off()關閉圖形設備。

我不能測試你的代碼,因爲我沒有數據集,但試試這個:

pdf(file = 'test.pdf', onefile = TRUE, paper = 'special', height = 11, width = 8.5) 

for(i in colSums(x)){ 
    plots <- quickplot(i) + 
     geom_bar(color= "#6267c1", fill="#6267c1") + 
     labs(title= "i", 
      x="i", 
      y="Count") + 
     theme(help() 
     plot.title = element_text(colour = "#453694"), 
     axis.title = element_text(colour ="#453694")) 
} 

dev.off() 

另見:https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/pdf.html

+0

非常感謝!我會給這個去:) – datastudent

0

以防萬一,這是有益的人,以下腳本最終爲我工作:

plot.auto <- function(data, list = as.list(colnames(data))){ 
     df <- data 
     ln <- length(names(data)) 
     for(i in 1:ln){ 

     plot <- quickplot(na.omit(df[,i],main=names(df)[i])) + 
      geom_bar() + 
      labs(title= colnames((df[,i])), 
       x=colnames((df)[i]), 
       y="y axis title") + 
# this makes the titles and text particular colours 
      theme(
      plot.title = element_text(colour = "#455876"), 
      axis.title = element_text(colour ="#455467"), 
# this puts the labels on an angle so they don't overlap 
      axis.text.x = element_text(angle = 30, hjust = 1))+ 
# this makes the title of the plot the same as the column name 
      ggtitle(colnames((df)[i])) + 
      geom_text(stat='count',aes(label=..count..),vjust=-0.3) 

     print(length(unique(df[,i]))) 
# this deletes any characters in the column names which will make saving 
difficult   
     save_name1<- gsub("/","or",as.character(colnames(df)[i])) 
     save_name<- gsub("\\?","",save_name1) 

#this tells you each title of the graph as the function runs  
     print(save_name) 

#this saves each graph in a folder which must be in your Working Directory 
eg. Auto_Plot_Folder (as a pdf) with the file the same as the column name 

     ggsave(plot,filename = 
paste("Auto_Plot_folder/",save_name,".pdf",sep =""),device ="pdf") 

     } 
    } 
相關問題