I want to plot multiple functions using for loop, but it always fails to load all of them and could not plot any functions.
For example:
set multiplot layout 2,2
set xrange [-pi:pi]
set yrange [-1:1]
f1(x)=sin(x)
f2(x)=cos(x)
f3(x)=sinh(x)
f4(x)=cosh(x)
plot for [i=1:4] sprintf("f%d(x)",i)
unset multiplot
and it says:
"data.plt" line 11: warning: Cannot find or open file "f1(x)"
"data.plt" line 11: warning: Cannot find or open file "f2(x)"
"data.plt" line 11: warning: Cannot find or open file "f3(x)"
"data.plt" line 11: warning: Cannot find or open file "f4(x)"
"data.plt" line 11: warning: Cannot find or open file "f5(x)"
"data.plt" line 11: warning: Cannot find or open file "f6(x)"
"data.plt" line 11: No data in plot
However, if I try to plot all of the funcitons one by one, it somehow works. For example:
set multiplot layout 3,2
set xrange [-pi:pi]
set yrange [-1:1]
f1(x)=sin(x)
f2(x)=cos(x)
f3(x)=sinh(x)
f4(x)=cosh(x)
plot f1(x)
plot f2(x)
plot f3(x)
plot f4(x)
unset multiplot
This can load all of functions without getting any errors.
Why does this happen, and how can I plot multiple functions using for loop? Since I use a string data when I write the name of the functions, that might be causing the problem, but even if so, I don't know any other ways.
I think the issue is that sprintf
returns a string, and a string argument to plot is interpreted as a data file name, not as an expression.
One approach is, instead of defining four functions, to define one function with two arguments, where the second selects the actual function to plot.
f(x,a) = \
(a == 1) ? sin(x) : \
(a == 2) ? cos(x) : \
(a == 3) ? sinh(x) : \
(a == 4) ? cosh(x) : \
0/0
set yrange [-5:5]
plot for [a=1:4] f(x,a)
I'm not sure how to actually build a string to use as an expression to plot. There is a macro substitution feature (see page 59 of the manual) but it only expands string variables, not general string expressions, so I don't see how to use it here. I suppose another approach would be to build up the entire plot
command as a string, and then use evaluate
, but that seems like a pain.