如何使用ggplot创建多个(6)图并将其保存为pdf文件?

时间:2018-03-21 16:42:06

标签: r pdf ggplot2

我有一个矩阵(pred_matrix,dim = 1e6,250),行是" pixelstacks"一个Landsat场景的250个NDVI值,我做了一个"模糊的cmeans"分类女巫6个中心(类),存储在列表results中。我现在想要绘制1e6行的每个类的随机子集。到目前为止,这是我快速而又脏的代码:

random_index <- floor(runif(10000, 1, 1e6+1))
random_cluster <- results[[6]]$cluster[random_index]
random_pred_matrix <- pred_matrix[random_index, ]
dates_subse_after_pred <- rdn_num[rm_na_pred_df]

random_res <- cbind(random_pred_matrix, random_cluster)
random_res <- t(random_res)
random_res <- cbind(c(dates_subse_after_pred, 1), random_res)

df_1 <- data.frame(random_res[1:250,c(TRUE, random_cluster==1)])
df_2 <- data.frame(random_res[1:250,c(TRUE, random_cluster==2)])
df_3 <- data.frame(random_res[1:250,c(TRUE, random_cluster==3)])
df_4 <- data.frame(random_res[1:250,c(TRUE, random_cluster==4)])
df_5 <- data.frame(random_res[1:250,c(TRUE, random_cluster==5)])
df_6 <- data.frame(random_res[1:250,c(TRUE, random_cluster==6)])


df_1.long <- melt(df_1, id.vars = 1)
df_1.long$X1 <- as.Date(df_1.long$X1)
df_2.long <- melt(df_2, id.vars = 1)
df_2.long$X1 <- as.Date(df_2.long$X1)
df_3.long <- melt(df_3, id.vars = 1)
df_3.long$X1 <- as.Date(df_3.long$X1)
df_4.long <- melt(df_4, id.vars = 1)
df_4.long$X1 <- as.Date(df_4.long$X1)
df_5.long <- melt(df_5, id.vars = 1)
df_5.long$X1 <- as.Date(df_5.long$X1)
df_6.long <- melt(df_6, id.vars = 1)
df_6.long$X1 <- as.Date(df_6.long$X1)


ggplot(df_1.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "lightblue")

ggplot(df_2.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "blue")

ggplot(df_3.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "lightgreen")

ggplot(df_4.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "green")

ggplot(df_5.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "pink")

ggplot(df_6.long) +
  geom_line( aes(x = X1, y= value, group = variable), color = "red")

在此之后,我刚刚在rstudio中按了6次导出按钮并将其全部插入到word文档中...

有没有办法在循环中执行此操作?或者甚至制作一个包含6个图的最终pdf?

2 个答案:

答案 0 :(得分:0)

单独的文件

我认为你所追求的是你的代码中有以下六次。

ggsave("filename.png", # or pdf if you like  
 plot = last_plot(), # or give ggplot object name as in myPlot,
 width = 5, height = 5, 
 units = "in", # other options c("in", "cm", "mm"), 
 dpi = 300)

例如,     库(GGPLOT2)

p1 <- ggplot(df_1.long) +
 geom_line( aes(x = X1, y= value, group = variable), 
  color = "lightblue")

 ggsave("df1.png", plot  = p1,  dpi = 300)

一体化

如果您想要一个pdf中的所有六个文件,请先执行

pdf("file_name.pdf")
# do your ggplots here
p1
p2
p6 
dev.off()

答案 1 :(得分:-2)

如果您使用的是Rstudio,我建议您在Rmarkdown文件中编写代码,然后直接导出为pdf。