Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts

Sunday, October 4, 2009

Changing labels in a Matlab whisker box plot

Given my recent Matlab experiences, I am tempted turn this blog into a Matlab-hater blog, but I will try to keep my cool.

Here's the next trick that I hope will save someone else a lot of time. It's about changing the label in a whisker box plot.

If you have the statistics toolbox installed, you can create whisker box plots with the boxplot() command.

Let's try:

>> boxplot(rand(10, 3), 'labels', {'Data A', 'Data B', 'Data XYZ'})

This creates a whisker box plots with the individual boxes labeled 'Data A', 'Data B' and 'Data XYZ':


Looks great, until you realize that you meant to label the third box 'Data C', and not 'Data XYZ'. Should be straight-forward to change, right? Isn't. Five minutes of clicking around and swearing took me nowhere.

So here's how to change the label. In the figure, click on Edit -> Figure properties. Next, click on any of the boxes. All boxes and all labels will be selected. Now, in Matlab's main window enter:

>> children = get(gco, 'Children');

This gives you a handle to all children of the currently selected object. The object you have selected right now is the boxplot, which is of type hggroup. Its i-th child is the label of the (n-i)-th box. So, the label of the the third box in the figure created above is the first child. It can be changed with

>> set(children(1), 'String', 'Data C');

And finally:

Better, isn't it? Better, yes, but the way there couldn't be less intuitive.

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?