在 Matlab 的图例中结合左右文本对齐

Combining left and right text justification in a legend in Matlab

我想让我的图例在 Matlab 中看起来像这样

[Category1 1.5%]

[Category2 2.3%]

其中文本左调整,百分比右调整。 有没有办法做到这一点?我正在考虑为图例中的每个条目添加第二个文本对象,但我想不出这样做的方法。现有的图例文本对象将图例本身作为父对象,但是,我无法向其添加新的文本对象。即使尝试按值复制文本对象也不起作用:

[l_h, object_h] = legend({'A', 'B'});
text_h = findobj(object_h,'Type','Text');

copyobj(text_h(1), text_h(1).Parent)

给我

Error using copyobj

Text cannot be a child of Legend.

您可以使用 sprintf 的技巧并使用每个字符具有恒定间距的字体,例如快递:

% demo from legend help:
x = 0:.2:12;
plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
% 3 legend entries which will have "TXT NUMBER%" format
text = {'First 10%','Second 20%','Third 30%'};
% make a copy of the text
numbers = text;

% split the text and numbers into two cell arrays
%    You probably have them split before here in your
%    code - I just do it here for demo.
for ii=1:length(text)
  entries = strsplit ( text{ii} );
  text{ii} = entries{1};
  numbers{ii} = entries{2};
end

% find the longest text entry.
mlen = max(cellfun ( @length, text ));

% create your format string - left justify the text.
formatstr = sprintf ( '%%-%is %%s', mlen );

% update the text which will go in the legend
for ii=1:length(text)
  text{ii} = sprintf ( formatstr, text{ii}, numbers{ii} );
end

% create the legend 
h = legend ( text );
% Change the font name - this is important!!
h.FontName = 'Courier';

好的,通过尝试,我找到了一种方法来做到这一点。 您不能在图例对象下创建新的 Text 对象,但是,还有另一个 Transform 对象包含可用于相同目的的图例标记。不确定逻辑是什么,但这有效:

[l_h, object_h] = legend({'A', 'B'});
text_h = findobj(object_h,'Type','Text');
marker_h=findobj(object_h,'Type','Patch');
legend_parent_h = marker_h(1).Parent;

p_h = copyobj(text_h(i), legend_parent_h);    

% now anything can be done with p_h