默认情况下,MATLAB将图例条目的文本部分放置在图中所用示例的之后。有什么办法可以扭转这种情况吗?例如,使用以下代码,图例中的第一项是深蓝色矩形,后跟文本I'm
;我希望它是相反的方式(即文本I'm
后跟一个深蓝色矩形)。我正在使用R2017b
示例代码:
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text = [ "I'm", "sorry", "Dave", "I'm", "afraid", "I", "can't", "do", "that" ];
Pie = pie( test_values );
legend( test_text );
答案 0 :(得分:4)
这是使用某些undocumented features的另一种选择:
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text = {'I''m'; 'sorry'; 'Dave'; 'I''m';'afraid';'I';'can''t';'do';'that'};
Pie = pie( test_values );
leg = legend(test_text,'Location','eastoutside');
drawnow % without this you can't accsses the legend entries
icons = [leg.EntryContainer.NodeChildren.Icon]; % an array with all the legend icons
leg.ItemTokenSize(1) = 0; % set the relative position of the text in the legend to x=0
% the following will probably need some fine tuning for a specific
% figure. It shifts the icons positions horizontally (i.e. only the first
% row has values other than zeros):
shift = [10 10 17 17
0 0 0 0
0 0 0 0];
for k = 1:numel(icons)
% move the icon (patch) border:
icons(k).Transform.Children.Children(1).VertexData = ...
icons(k).Transform.Children.Children(1).VertexData+shift;
% move the icon (patch) fill:
icons(k).Transform.Children.Children(2).VertexData = ...
icons(k).Transform.Children.Children(2).VertexData+shift;
end
% the following will probably need some fine tuning for a specific
% figure. It expands the legend box horizontally:
shift = [0 0 1 1
0 0 0 0
0 0 0 0];
leg.BoxEdge.VertexData = leg.BoxEdge.VertexData+shift; % the box border
leg.BoxFace.VertexData = leg.BoxFace.VertexData+shift; % the box face
答案 1 :(得分:3)
我认为这是不可能的,但是如果给图例提供空白文本然后在外部显示文本,则可以通过以下方法解决此问题:
figure;
Pie = pie( test_values );
emptyLegend = repmat({''},9,1);
h = legend( emptyLegend );
text(repmat(0.8,9,1),[0.8:-0.1:0]',test_text)
set(h,'Position',[0.9 0.5 0.05 0.35])
答案 2 :(得分:3)
这是基于EBH在其解决方案中使用的方法的替代解决方案。
我希望这不会被视为窃,以防万一,请发表评论,然后删除答案。
我提出的解决方案不使用任何未记录的功能,并且已在R2015b上进行了测试;我不知道它是否可以在以后的版本中使用。
想法是:
legend
函数text
patch
(方框)的adta X
的原始坐标最后一步包含一个画框,因为它需要缩放补丁的大小以将其保存在图例框中。
此外,由于R2015b不能按照问题中的要求处理字符串,因此我修改了图例文本的定义。
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text = { 'I''m', 'sorry', 'Dave', 'I''m', 'afraid', 'I' 'can''t', 'do', 'that' };
Pie = pie( test_values );
% get all the output from the legend function
[lgd,icons,plots,txt]=legend( test_text );
% Get the number of elements in the legend
n_items=length(icons)/2
% Loop over the legend's items
for i=1:n_items
% Get the original position of the text item
orig_txt=icons(i).Position
% Get the original coordinated of the Vertices of the patch
orig_mark=icons(i+n_items).Vertices
% Set the position of the text to the original coordinate of the first
% "X" of the patch
icons(i).Position=[orig_mark(1) orig_txt(2)]
% Set the "X" coordinates of the patch to the original "X" position of
% the text and scale it
icons(i+n_items).Vertices(:,1)=icons(i+n_items).Vertices(:,1)+orig_txt(1)*.7
end