Thursday, September 10, 2009

Deleting legend entries in Matlab plots

Matlab has been a constant source of annoyance and rage since I started writing my thesis. Using it in a dual screen environment, trying to export figures, and the source file editor's obscure keyboard short-cuts often brought me close to insanity.

But today I want to share a nice trick with you that I have just found out: How to delete legend entries in a Matlab plot.

Why would anyone want to do that? An example is the errorbarbar script. It adds errorbars to your bar plot. A pretty useful thing! What is not so useful is the fact that the errorbars themselves appear in the legend. See for yourself:

>> values=10*rand(5, 3);
>> errors=rand(5,3);
>> errorbarbar(values, errors);

The resulting image, after a legend has been inserted using Insert -> Legend:


The data4, ..., data 5 entries are both useless and annoying.

Here's the solution. In the figure window, click Edit -> Properties. Then, select an error bar and enter

>> hasbehavior(gco, 'legend', false);

Do this for each bar in the first group. Then delete the old legend and insert a new one using Insert -> Legend. Voilà:


Looks much better, doesn't it?

20 comments:

  1. Thanks! Just what I was looking for.

    ReplyDelete
  2. Another way:

    p(1) = plot(rand(20,1),'r')
    hold on
    p(2) = plot(rand(20,1),'g')
    p(3) = plot(rand(20,1),'b')

    % add only desired legend entries
    legend([p(1) p(3)],'data1','data3')

    ReplyDelete
  3. thank you, thank you, thank you.

    ReplyDelete
  4. Thanks a lot..!! saved me some time

    ReplyDelete
  5. you can change the keyboard shortcuts for the editor from emacs style to windows style. Use file->preferences->keyboard->shortcuts->windows default set

    ReplyDelete
  6. I really like this site, it's so important to know more about this topic, keep it up and of course every time I have time I'll love to check out again

    ReplyDelete
  7. Thanks a lot. I was struggling with this issue for a long time.
    SB

    ReplyDelete
  8. Thanks a lot for the Anonymous at May 27, 2010 1:54 PM
    It's easy and works fine!

    ReplyDelete
  9. Thank you! Just what I was looking for.

    ReplyDelete
  10. Thank you!!!! You just saved me many hours of work!

    ReplyDelete
  11. This didn't work on my MATLAB R2011a,,, what should I do!! HELP!!

    ReplyDelete
  12. Thanks, very useful!

    ReplyDelete
  13. Worked a treat, thank you

    ReplyDelete
  14. Danke_Thank you !!!

    ReplyDelete
  15. couldn't find this answer anywhere else. thank you!

    ReplyDelete
  16. "Insightful" is the perfect word to describe this wonderful writing of yours. The artistic blend of this subject with your tone of writing made this a great read. Much love 😘.
    How to bottom

    ReplyDelete