2

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

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
tqjustc
  • 3,624
  • 6
  • 27
  • 42
  • 1
    I think, the following link provides best answer to your query, without needing to replot. http://stackoverflow.com/a/39104135/842808 – Abhinav Jan 21 '17 at 06:33

2 Answers2

3

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

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Note that this solution requires explicitly returning and keeping track of the graphics objects (h1, h2) as they are plotted. For a similar solution that does not require that, see my answer in a related question here: https://stackoverflow.com/a/66681832/6292794 – JMikes Mar 17 '21 at 22:02
1

In case, you have already made the plots or if you added some plot at the end, which want to reorder to somewhere in middle, you can try this way:

1) Go to show Plot Tools and Dock Figure.

2) Delete the data (which you want to move to bottom). Then undo delete.

3) Refresh legend.

SKPS
  • 5,433
  • 5
  • 29
  • 63
  • This seems to have stopped working somewhere around R2017a. Now if I restore the lines they end up in the original order and nothing changes. Is there a workaround? – Emil Jul 12 '17 at 17:55