0
$\begingroup$

I am using the command lines:

data = Import["file*.txt", "CSV"]
ListLinePlot[data]

to plot lists of points.

As you can notice, my file name is file*.txt. I use that star because I have multiple lists of points to plot.

The problem is that the command from above creates a single graphic, where the points from each file are colored differently.

How can I create a single graphic for each file? For example if I have 3 files (file1.txt, file2.txt and file3.txt) there should be 3 idependent graphics as an output.

$\endgroup$
1
  • 1
    $\begingroup$ ListLinePlot@*Import[#,"CSV"]&/@FileNames["file*.txt"] $\endgroup$
    – C. E.
    May 2, 2015 at 17:12

1 Answer 1

4
$\begingroup$

In Mathematica an iteration over lists can be produced by clever use of operators such as /@ (Map) or @@ (Apply), so you could write:

data = Import["file*.txt", "CSV"]
ListLinePlot /@ data

The result will be a list, that contains the different ListLinePlots.

Maybe in your case its easier to work with For-loops, if you want to add additional commands like Export.

SetDirectory[NotebookDirectory[]]
data = Import["file*.txt", "CSV"]

For[i = 1, i <= Length[data], i++,
  plot = ListLinePlot[data[[i]]];
  Print[plot];
  Export[ToString[i] <> ".pdf", plot]
]

The following aproach dont imports everything at once, it imports every single file separatly inside the For-loop. The wildcard * is used before this happens with FileNames.

SetDirectory[NotebookDirectory[]]
files = FileNames["file*.txt"]

For[i = 1, i <= Length[files], i++,
  data = Import[files〚i〛, "CSV"];
  plot = ListLinePlot[data];
  Print[plot];
  Export[FileBaseName[files[[i]]] <> ".pdf", plot]
]
$\endgroup$
3
  • $\begingroup$ I think your last suggestion should be your first, but otherwise good. +1 $\endgroup$
    – C. E.
    May 2, 2015 at 17:51
  • 1
    $\begingroup$ @Pickett You are right, i just changed that. $\endgroup$
    – sacratus
    May 2, 2015 at 17:56
  • $\begingroup$ One might also use Scan[]: Scan[Block[{data = Import[#, "CSV"], plot}, Print[plot = ListLinePlot[data]]; Export[FileBaseName[#] <> ".pdf", plot]] &, FileNames["file*.txt"]] $\endgroup$ May 3, 2015 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.