【问题标题】:ggplot in loop reading CSV filesggplot循环读取CSV文件
【发布时间】:2021-04-16 22:56:33
【问题描述】:

我有几个包含 3 列的 .csv 文件。我想绘制前 2 个图形。ggplot 制作了一些漂亮的图形,但我想自动化这项任务,因为有数百个文件。我已经从这个站点尝试了几种方法,但没有一个对我有用。我想用lapply 来做这件事,但我遇到的每一个例子都失败了。

我会很感激使用ggplot 的答案,但否则我最终会用 plot 做同样的事情。

这是我的代码:

Star2 <-read.table("lista2.txt",stringsAsFactors=FALSE)[,c(1)]

for (i in 1: length(Star2)){ 
   print(ggplot(read.csv(Star2[i]) ,
                aes(x = V1, y = V2, color = "red")) +
           geom_point(colour= "orange") +
           scale_y_reverse(limit = c(6.60,6.45), expand=c(0,0)) +
           ggtitle("CURVA DE FASE") + 
           geom_smooth (colour ="blue" ,span = 0.2) +
           xlab("Fase") + ylab("Mag"))


   ggsave(phase3, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}

【问题讨论】:

  • 你能告诉我们一些你尝试过的东西吗?通常人们会帮助调整你的代码,但不会为你写东西。
  • Star2
  • 什么不起作用?您可以使用 ggsave 来保存数字。
  • 好的,我用 ggsave 搜索一些东西并将其添加到其中。当我这样做时,它没有显示任何图表。保罗,你是在跟一个超级初学者说话吗……谢谢!
  • 欢迎来到 SO!请尝试使用代码块将您的代码放入问题中,这样其他人可以更轻松地查看和帮助您。

标签: r loops ggplot2


【解决方案1】:

你可以试试:

library(ggplot2)

filenames <- list.files('/folder/of/csv/files', pattern = '\\.csv$', full.names = TRUE)

lapply(filenames, function(x) {
  data <- read.table(x,stringsAsFactors = FALSE)
  ggplot(data, aes(x = V1, y = V2, color = "red")) +
    geom_point(colour= "orange") +
    scale_y_reverse(limit = c(6.60,6.45), expand=c(0,0)) +
    ggtitle("CURVA DE FASE") + 
    geom_smooth (colour ="blue" ,span = 0.2) +
    xlab("Fase") + ylab("Mag") -> phase3

  ggsave(phase3, file=paste0("plot_", tools::file_path_sans_ext(basename(x)),".png"), 
         width = 14, height = 10, units = "cm")
})

【讨论】:

  • 好极了,罗纳克! 5天试图让这部分脚本出来..!它们是我第一次尝试使用 GGplot,我设法一个一个地制作图表,但我需要很多图表,我的文件实际上是:“.Out”只需在您的代码中将 .csv 更改为 .out:... .无限感谢!我在 apply 系列中看到了很多想法,并在我的 RScript 代码中尝试了替代方案,但都没有奏效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
相关资源
最近更新 更多