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.