From 44c3654922390dd2d71a5714d328ead47a823524 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Ry=C3=BBk=29?=
 <stepan@adjemian.eu>
Date: Fri, 19 May 2023 18:37:03 +0200
Subject: [PATCH] Add option --with-legend.

---
 src/utilities/dplot/dplot.m | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/src/utilities/dplot/dplot.m b/src/utilities/dplot/dplot.m
index 2f71120..2da05d0 100644
--- a/src/utilities/dplot/dplot.m
+++ b/src/utilities/dplot/dplot.m
@@ -78,6 +78,10 @@ function dplot(varargin)
     ts = cell(1, length(data)*length(expressions)); l = 0;
     Expressions = cell(size(expressions));
 
+    if iswithlegend(varargin)
+        legendnames = {};
+    end
+
     for i=1:length(data)
         for j=1:length(expressions)
             % Check that brackets are balanced
@@ -105,6 +109,9 @@ function dplot(varargin)
             Expressions{j} = rewrite(expressions{j}, listofvariables, i);
             l = l+1;
             ts{l} = eval(Expressions{j});
+            if iswithlegend(varargin)
+                legendnames{l} = sprintf('%s [%s]', expressions{j}, names{i});
+            end
         end
     end
     %
@@ -127,6 +134,9 @@ function dplot(varargin)
     id = ax.XTick;
     dd = strings(range(id));
     ax.XTickLabel = dd;
+    if iswithlegend(varargin)
+        legend(legendnames{:}, 'Location','SouthOutside','Orientation','horizontal','Box','off')
+    end
 end
 
 function expr = getexpressions(cellarray)
@@ -163,6 +173,20 @@ function names = getdseriesnames(cellarray)
     names = cellarray(dpos+1);
 end
 
+function bool = iswithlegend(cellarray)
+
+% Return true if and only if a legend below the plot is required.
+%
+% INPUTS
+% - cellarray     [char]      1×n cell array of row char arrays.
+%
+% OUTPUTS
+% - bool          [dates]     scalar.
+
+    bool = contains('--with-legend', cellarray);
+
+end
+
 function range = getrange(cellarray)
 
 % Return period range for the plots.
-- 
GitLab