我正在尝试为数据集的每一列创建一个图表(使用quickplot),并将其作为pdf保存到文件夹中 - 非常感谢!
到目前为止,我已经制作了一个测试数据框(在我尝试使用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)
但是,这似乎出现了很多错误,所以我认为我做得不对。
答案 0 :(得分:1)
尝试使用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
答案 1 :(得分: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")
}
}