Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend; text/description before key/colour?

By default MATLAB puts the text part of a legend entry after the sample of what is used in the plot. Is there any way to reverse this? For example, using the below code the first entry in the legend is a dark blue rectangle followed by the text I'm; I'd like it to be the other way around (i.e. the text I'm followed by a dark blue rectangle). I am using R2017b

Example code:

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 );
like image 583
Steve Avatar asked Dec 24 '22 01:12

Steve


1 Answers

Here is another option using some 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

enter image description here

like image 69
EBH Avatar answered Jan 09 '23 16:01

EBH