Search code examples
matlabplotlegendmatlab-figurefigure

how to change the sequence of the legend


I want to change the sequence of the legend.

See the figure. I want the sequence to be: green and data2, blue and data3, black and data4, red and data1.

Could anyone give a demo?

enter image description here


Solution

  • Change the order in which the plots are added to the figure, and then call legend normally. That should do it.


    You can also do it as follows. First get handles to the individual plots:

    h1 = plot(1:5);
    hold on
    h2 = plot(11:15, 'r');
    

    Then call legend specifying the order:

    legend([h1 h2],'plot1','plot2')
    

    or

    legend([h2 h1],'plot2','plot1')
    

    enter image description here

    enter image description here