Search code examples
matlabplotmatlab-figurelegendlegend-properties

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

Solution

  • This is an alternative solution based on the approach used by EBH in his solution.

    I hope it will not be considered a plagiarism, in case I apologise, please, put a comment and I'll delete my answer.

    The solution I propose does not use any undocumented feature and has been tested on R2015b; I do not know if it will work on later Releases.

    The idea is:

    • call the legend function by requiring all the output paramentes
    • work on the second output parameter
    • the first half of data in this parameter are the ones of the text of the legend
    • the second half are the adta of the patch of the legend (the boxes)
    • loop over this parameter
    • Get the original position of the text item
    • Get the original coordinated of the Vertices of the patch
    • Set the position of the text to the original coordinate of the first X of the patch
    • Set the "X" coordinates of the patch to the original "X" position of the text and scale it

    The last step contains a drawbak, because it requires to scale the size of the patchs to hold them inside the legend box.

    Also, I've modified the definition of the text of the legend since R2015b does not handle the string as per in the question.

    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
    

    enter image description here