How do I add a legend to a boxplot in MATLAB?
47 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2014 年 4 月 25 日
編集済み: MathWorks Support Team
2024 年 2 月 2 日
I created a boxplot and would like to add a legend to it, but when I call legend I get the following warning message and there is no legend in the plot figure:
Warning: Plot empty.
> In legend at 286
Is it possible to add a legend to a box plot? My code is:
figure;
colors = [1 0 0; 1 0 0; 0 0 1; 0 0.5 0; 0 0.5 0; 0 0.5 0];
x = boxplot(rand(100,6),'Colors',colors);
legend('Group A','Group B','Group C')
採用された回答
MathWorks Support Team
2024 年 2 月 2 日
編集済み: MathWorks Support Team
2024 年 2 月 2 日
As of MATLAB R2020a, "boxchart" is an alternative to "boxplot" and allows the creation of a legend. The following documentation illustrates some of the advantages of a "boxchart":
The following documentation demonstrates the use of "boxchart":
For MATLAB R2014a and prior, you can explicitly pass to the "legend" function the handle to the axes in which the box plot is drawn:
figure;
colors = [1 0 0; 1 0 0; 0 0 1; 0 0.5 0; 0 0.5 0; 0 0.5 0];
x = boxplot(rand(100,6), 'Colors',colors);
% findall is used to find all the graphics objects with tag "box", i.e. the box plot
hLegend = legend(findall(gca,'Tag','Box'), {'Group A','Group B','Group C'});
Depending on the number of variables that you have, you might not obtain the right color for each legend element. Use the following trick to manually change the color of each legend element:
% Among the children of the legend, find the line elements
hChildren = findall(get(hLegend,'Children'), 'Type','Line');
% Set the horizontal lines to the right colors
set(hChildren(6),'Color',[1 0 0])
set(hChildren(4),'Color',[0 0 1])
set(hChildren(2),'Color',[0 0.5 0])
In R2014b and after, the Children property of Legend does not return the line plots. A workaround is as follows:
box_vars = findall(gca,'Tag','Box');
hLegend = legend(box_vars([3,2,4]), {'Group 1','Group 2','Group 3'});
2 件のコメント
Dyuman Joshi
2023 年 11 月 23 日
Sebastian Lopez Saavedra (I can't seem to tag the profile directly) notes -
"This reply has to be updated because it doesn't work in Matlab 2023"
Dyuman Joshi
2023 年 11 月 23 日
As an alternative, you can use the boxchart function, which does support the functionality to directly use legends.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!