Multiple lines in histogram legend

2019-09-14 06:46发布

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

1条回答
在下西门庆
2楼-- · 2019-09-14 07:22

Per the DisplayName documentation, a newline character \n needs to be injected into the text, and this can easily be done through sprintf. One small but important complication is that escaping the standard LaTeX active character \ is required, so sprintf doesn't think LaTeX commands are one of its special characters (some variable names were changed to ensure the code runs):

xErr = randn(1,1000);
[mu, sig] = normfit(xErr);
h = histogram(xErr, 100, 'Normalization','pdf');
set(h,...
   'DisplayName',...
   sprintf([...
       'Standard deviation $\\sigma_{x} = $ ', num2str(sig),...
       '\nMean $\\mu_x = $ ', num2str(mu)]));
hl = legend('Location', 'NorthWest');
set(hl,'Interpreter','latex');

I would personally use

xErr = randn(1,1000);
[mu, sig] = normfit(xErr);
histogram(xErr, 100, 'Normalization','pdf');
legText = {...
    sprintf([...
        'Standard deviation $\\sigma_{x} = %9.7f$  \n ',...
        'Mean               $\\mu_x      = %9.7f$'    ],...
        [sig,mu])...
    };
legend(legText,'Location', 'NorthWest','Interpreter','latex'); 

but that's just aesthetics.

查看更多
登录 后发表回答