Multiple lines in histogram legend

℡╲_俬逩灬. 提交于 2019-12-13 06:36:16

问题


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:


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.



来源:https://stackoverflow.com/questions/41779825/multiple-lines-in-histogram-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!