30

This question is related to Loop structure inside gnuplot? and the answer there by DarioP.

gnuplot 4.6 introduced the do command. How can I use this to loop over an array of for example files and colors? What is the correct syntax?

colors = "red green #0000FF"
files = "file1 file2 file3"

do for [i=1:3] {
  plot files(i).".dat" lc colors(i)
}
Just a student
  • 10,560
  • 2
  • 41
  • 69
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108

1 Answers1

48

If you want to have all files in a single plot, you need to use plot for[... (supported since version 4.4). Looping over several plot commands with do for (supported only since version 4.6) works only in multiplot mode.

The following two solutions both plot all data in one graph, but differ a bit in the iterations.

The first solution uses word to extract a word from a string directly when plotting.

colors = "red green #0000FF"
files = "file1 file2 file3"
plot for [i=1:words(files)] word(files, i).'.dat' lc rgb word(colors, i)

The second solution changes the linetype and then iterates directly over the word list instead of using an index.

colors = "red green #0000FF"
files = "file1 file2 file3"
set for [i=1:words(colors)] linetype i lc rgb word(colors, i)
plot for [file in files] file.'.dat'
Christoph
  • 47,569
  • 8
  • 87
  • 187
  • I only just got around to test it now. I prefer your second solution, which does not require multiplot mode. It works. Beautiful solution. I did not know about "words" and "word" despite having used gnuplot for more than a decade. Thank you. – tommy.carstensen Sep 08 '13 at 00:00
  • 1
    @tommy.carstensen Your approach with `do for .. plot` works only in `multiplot` mode. Both my solutions use `plot for [...` and give a single plot. I refrased my anwer to clarify this. – Christoph Sep 08 '13 at 14:01
  • 3
    Thanks for clarifying. I also learned that "word" and "words" are covered in the string variables demo for those that want to study that in greater detail: http://gnuplot.sourceforge.net/demo/stringvar.html – tommy.carstensen Sep 08 '13 at 17:32