Bernhard
Bernhard

Reputation: 96

Gnuplot workflow involving loops of fits that get multiplotted

I want to do the following in gnuplot: read my files, which are conveniently labeled "filenameN.txt", where N is the Nth file.

Fit some polynom fN(x)to the data, using aN, bN,... and plot all of those in a single graphic (multiple plots) using multiplot

However, I cannot get this to work using the loops available in gnuplot. What does work is for example creating one file, that does what I want for N, and then running an external loop that passes N=1...M.

This results in M plots, but not in a single multiplot.

For this to work I need to assign variables with variable names (f1, f2, ... a1, a2, ..., ...) for the fits (since I potentially want to use all of them together somehow)

I also want the plot loop to produce simple plots in a multiplot (each containing data and its fit, M times, not a multiplot where the first plot contains all of the lines, and the rest of the plots are empty.

So I have two questions then:

Upvotes: 3

Views: 1172

Answers (1)

Christoph
Christoph

Reputation: 48390

You can define you function depending on N like:

fstr(N) = sprintf('f%d(x) = a%d*x**2 + b%d*x + c%d', N, N, N, N)
eval(fstr(1))

This defines the function f1(x) = a1*x**2 + b1*x + c1. For the fitting function you must do the same:

fitstr(N) = sprintf('fit ''filename%d.txt'' f%d(x) via a%d,b%d,c%d', N, N, N, N, N)

Then you first do all the fits:

do for [i=0:N] {
    eval(fstr(i))
    eval(fitstr(i))
}

and then plot each data file with points and the corresponding fit with lines. In order to have all plots in one graph, you must use a single plot command and separate the plots with a comma.

But in order to group fit and data in the key you can use replot to add plots. And you must use macros to get the correct function in the plots, eval doesn't work here:

set style data points
set style func lines
plot 'filename0.txt' lt 1, f0(x) lt 1
set macros
do for [i=1:N] {
    f = sprintf('f%d(x)', i)
    replot sprintf('filename%d.txt', i) lt (i+1), @f lt (i+1)
}

Just put everything together in one file and run gnuplot with it.

Upvotes: 3

Related Questions