无法在循环中绘制多个图?

时间:2015-05-05 11:52:11

标签: r loops ggplot2

我的多个图的代码是

    for (i in 3:5) {
        #paste(names(normalized_ge_data))
        file_name = paste(as.character(i), ".png")
        png(file_name)
        g + geom_boxplot(aes(fill=factor(ge_data$hasServiced))) + geom_jitter()
        dev.off()
    }

我想拥有像3.png,4.png等文件。 怎么做到这一点?

4 个答案:

答案 0 :(得分:2)

我认为对于ggplot来说,最好的方法是使用ggsave()函数:

for (i in 3:5) {
      qplot(mtcars[, i])
      ggsave(file = paste0("plot_", i, ".png"))
    }

此处的文档:http://docs.ggplot2.org/0.9.2.1/ggsave.html

答案 1 :(得分:1)

按照上面@Daniel的建议,这有效:

//Create an array for 2 different prefabs.
AssetBundleBuild[] buildMap = new AssetBundleBuild[2];

//Make a buildMap for the first prefab.
AssetBundleBuild buildInfo1 = new AssetBundleBuild();
//The name of the bundle that the prefab will be saved as.
buildInfo1.assetBundleName = bundle1Name+".unity3d";

//Only one file for this prefab.
string[] prefabs1 = new string[1];
//The full path to the prefab.
prefabs[0] = prefab1Path;
buildInfo1.assetNames = prefabs1;

buildMap[0] = buildInfo1;


AssetBundleBuild buildInfo2 = new AssetBundleBuild();
//The name of the bundle that the prefab will be saved as.
buildInfo2.assetBundleName = bundle2Name+".unity3d";

//Only one file for this prefab.
string[] prefabs2 = new string[1];
//The full path to the prefab.
prefabs[0] = prefab2Path;
buildInfo2.assetNames = prefabs2;

buildMap[0] = buildInfo2

//Save the prefabs as bundles to the "bundleFolder" path.
BuildPipeline.BuildAssetBundles(bundleFolder, buildMap)

答案 2 :(得分:1)

我用一些示例数据尝试了您的示例,它对我有用:

library(sjmisc)
library(ggplot2)
data(efc)

for (i in 3:5) {
  file_name = paste0(as.character(i), ".png")
  png(file_name)
  plot(ggplot(efc, aes(x = 1, y = e17age)) + geom_boxplot() + geom_jitter())
  dev.off()
}

没有plot,只创建了白色的空png。

答案 3 :(得分:1)

如果OP严格查看print图,最好的方法可能是在循环期间将图存储在列表中,然后打印列表中的每个项。这是一个建议:

library(ggplot2)

plot_list <- list()

for (ii in 1:5){
  temp_df <- data.frame(x=rnorm(n=15, mean=0, sd=5),
                        y=rnorm(n=15, mean=0, sd=5),
                        z=rnorm(n=15, mean=0, sd=5))
  temp_plot <- ggplot(temp_df, aes(x=x, y=y, color=z))+
    geom_point()+
    theme_bw()+
    ggtitle(paste("Group", ii))
  plot_list[[ii]] <- temp_plot
}

lapply(plot_list, print)

当然,您可以更改lapply调用以使用ggsave或您想用来保存图表的任何函数。