Creating a Legend for a Boxplot with Two Colors

Hi, I need help inserting a legend for a boxplot with two colors (red & blue). My code for this is:
boxplot(data, 'notch', 'on', 'symbol', '*','colors','rb');
legend('Label1','Label2');
But I get no legend and it says "Warning: Plot empty" in the command window. Any help on this matter would be much appreciated. Thank you.

 採用された回答

Walter Roberson
Walter Roberson 2011 年 6 月 28 日

2 投票

It isn't a bug. The annotations for the boxes have their IconDisplayStyle property set 'off' which is a signal that they are not to be included in legends.
You can include them deliberately by using
legend(findobj(gca,'Tag','Box'),'Label1','Label2')
but note that the boxes all have the same color (at least with the call you use) so the legend lines will be in the same color as each other.

5 件のコメント

Danny
Danny 2011 年 6 月 28 日
Thank you, that did exactly what I wanted it to. Actually the call I used ('colors','rb') makes every odd numbered box red and every even numbered box blue. Thanks again for such a quick response.
Oleg Komarov
Oleg Komarov 2011 年 6 月 29 日
@Walter: enlightening as usual.
Billy
Billy 2014 年 2 月 17 日
Is there a way to make the legend lines have different colors in this case, e.g. when using: legend(findobj(gca,'Tag','Box'),'Label1','Label2')?
Isabel Chen
Isabel Chen 2016 年 6 月 15 日
I am using Matlab 2016a, and with the code above, I get the following error message:
Warning: Ignoring extra legend entries.
> In legend>set_children_and_strings (line 643)
In legend>make_legend (line 328)
In legend (line 257)
The plot looks fine, apart from the legend entries in the wrong order. Any ideas?
Walter Roberson
Walter Roberson 2016 年 6 月 16 日
In your line similar to
legend(findobj(gca,'Tag','Box'),'Label1','Label2')
you need to supply as many labels as you have columns in your data. boxplot creates one object with tag Box for each column of data.

サインインしてコメントする。

その他の回答 (1 件)

Oleg Komarov
Oleg Komarov 2011 年 6 月 28 日

1 投票

Use the option labels, dunno if it is a bug but legend doesn't seem to work.

カテゴリ

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by