直方图图例中的多行 [英] Multiple lines in histogram legend

查看:90
本文介绍了直方图图例中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制带有由两行组成的图例的直方图. 运行以下代码会导致错误:

I am trying to plot a histogram with a legend that consists of two lines. Running the following code leads to the error:

使用matlab.graphics.chart.primitive.Histogram/set时出错

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');

我也直接使用histogram命令尝试了DisplayName属性,但这也不起作用.根据这个问题单元格的尺寸也必须与错误所指出的句柄数相匹配.

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')];

是否有一种简单的方法来获取直方图的图例中的两行?

我正在使用Matlab R2016b

I am using Matlab R2016b

推荐答案

每个 DisplayName文档,需要在文本中插入换行符\n,这可以通过

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');

我会亲自使用

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'); 

但这只是美学.

这篇关于直方图图例中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆