I am trying to plot a histogram with a legend that consists of two lines. Running the following code leads to the error:
Error using matlab.graphics.chart.primitive.Histogram/set
Value cell array handle dimension must match handle vector length.
xErr = randn(1,1000);
[mu, sig] = normfit(xErr);
h = histogram(xErr, 100, 'Normalization','pdf');
% The following command causes the error
set(h_xErr, {'DisplayName'}, {['Standard deviation $\sigma_{x} = $ ', num2str(sigX)]; ['Mean $\mu_x = $ ', num2str(muX)]});
hl = legend('Location', 'NorthWest');
set(hl,'Interpreter','latex');
I also tried the DisplayName property directly with the histogram command but this doesn't work either. According to this question it is necessary that the dimension of the cell array also matches the number of handles which the error states too.
I thought of adding another handle with still the same error.
h = [h; histogram(xErr, 100, 'Normalization','pdf')];
Is there a simple way to get two lines in the legend of a histogramm?
I am using Matlab R2016b
Per the
DisplayName
documentation, a newline character\n
needs to be injected into the text, and this can easily be done throughsprintf
. One small but important complication is that escaping the standard LaTeX active character\
is required, sosprintf
doesn't think LaTeX commands are one of its special characters (some variable names were changed to ensure the code runs):I would personally use
but that's just aesthetics.