是否可以定义其中定义了多个语句的函数?
我想通过定义函数来自动化创建堆积图所涉及的一些计算。特别是,我希望有类似的东西
mp_setup(bottom_margin, top_margin) = \
set tmargin 0; \
set bmargin 0; \
mp_available_height = 1.0 - top_margin - bottom_margin; \
mp_current_height = bottom_margin;
mp_plot(plot_height) = \
mp_plot_size = plot_height * mp_available_height; \
set origin 0,mp_current_height; \
set size 1,mp_plot_size; \
mp_current_height = mp_current_height + mp_plot_size;
Run Code Online (Sandbox Code Playgroud)
预期用途是:
...
set multiplot
mp_setup(0.05, 0.05)
mp_plot(1.0/3.0)
plot ...
mp_plot(2.0/3.0)
plot ...
Run Code Online (Sandbox Code Playgroud)
这应该会自动导致图很好地堆叠,而无需我计算每个图的原点和大小。
上面定义函数的方法不起作用,因为函数定义的解析似乎在第一次出现 ; 时结束;
。但这些分号是必要的,以便分隔每个语句(否则,我们的set tmargin 0 set bmargin 0...
语句是无效的)。
Gnuplot 似乎也不支持任何分组语句的方式(如{...}
C/C++ 中的);或者至少,我从来没有遇到过。
我知道存储多个函数并评估它们的唯一方法是使用宏:
mp_setup = "<as above>"
mp_plot = "<as above>"
Run Code Online (Sandbox Code Playgroud)
但这里的问题是宏不允许传入参数,而是必须事先声明每个变量,如下所示:
...
set multiplot
top_margin = 0.05
bottom_margin = 0.05
@mp_setup
plot_height = 1.0/3.0
@mp_plot
plot ...
plot_height = 2.0/3.0
@mp_plot
plot ...
Run Code Online (Sandbox Code Playgroud)
这个解决方案虽然应该可行,但并不那么优雅。
没有其他方法可以做到这一点吗?
不,不可能定义这样的函数。在 gnuplot 中,用户定义的函数不能包含set
,unset
或其他命令。仅允许返回数字或字符串变量的表达式。在这里,您可以有多个表达式,用逗号分隔:
a = 0
f(x) = (a = a + 1, a + x)
print f(1)
print f(1)
Run Code Online (Sandbox Code Playgroud)
除了使用宏 ( @var
) 的解决方案之外,我更喜欢在函数内构造字符串并调用eval
:
set_margin(s, v) = sprintf('set %smargin at screen %f;', s, v)
set_margins(l, r, b, t) = set_margin('l', l).set_margin('r', r).set_margin('b', b).set_margin('t', t)
eval(set_margins(0.1, 0.95, 0.15, 0.98))
Run Code Online (Sandbox Code Playgroud)
对于多图布局的具体情况,您还可以参阅删除 gnuplot multiplot 中的空白。