r语言 - 将单独文件中的试验叠加到一个 ggplot 图上



我正在尝试绘制具有多个试验的图表(来自单独的文本文件(。在下面的例子中,我用"射速"变量绘制"place"变量,当我单独使用 ggplot 时它可以工作:

a <- read.table("trial1.txt", header = T)
library(ggplot2)
ggplot(a, aes(x = place, y = firing_rate)) + geom_point() + geom_path()

但是当我尝试创建一个 for 循环来遍历文件夹中的每个试用文件并将其绘制在同一张图上时,我遇到了问题。这是我到目前为止所拥有的:

 files <- list.files(pattern=".txt")
 for (i in files){
   p <- lapply(i, read.table)
   print(ggplot(p, aes(x = place, y = firing_rate)) + geom_point() + geom_path())
 }

它给了我一个"错误:data必须是数据框或其他可由fortify()强制的对象,而不是列表"消息。我是新手,所以我不确定该怎么做。

提前感谢您的帮助!

一般来说,

避免循环是 R 中最好的方法。由于您正在使用ggplot您可能有兴趣使用 tidyverse 中的 map_df 函数:

首先创建一个读取函数,并将文件名作为试用标签包含在内:

readDataFile = function(x){
a <- read.table(x, header = T)
a$trial = x
return(a)
}

接下来map_df

dataComplete = map_df(files, readDataFile)

这会在每个文件上运行我们的小函数,并将它们全部组合到一个数据框中(当然,假设它们的格式兼容(。

最后,您几乎可以像以前一样绘制,但可以根据试验变量进行区分:

ggplot(dataComplete, aes(x = place, y = firing_rate, color=trial, group=trial)) + geom_point() + geom_path()

最新更新