複数の行・列で構成される凡例(legend)を作成できますか?
117 views (last 30 days)
Show older comments
MathWorks Support Team
on 28 Apr 2017
Edited: MathWorks Support Team
on 21 Sep 2021
通常、legend 関数では、1列の凡例を作成しますが、複数行もしくは複数列で構成される凡例を作成する方法を教えてください。
特に、scatter 関数などで Figure を作成した場合、データ点数が多いと凡例が長くなり、Figure 内に収まりません。
Accepted Answer
MathWorks Support Team
on 13 Sep 2021
Edited: MathWorks Support Team
on 21 Sep 2021
MATLAB 9.4(R2018a) 以降では、凡例のオブジェクト(Legend オブジェクト)の NumColumns プロパティを指定することで、凡例を行列の構成で表示することが可能です。
x = linspace(0,10);
f = 0.1:0.1:0.6;
figure; hold on
for n = 1:length(f)
y = sin(f(n)*x);
plot(x,y,'DisplayName',['sin(',num2str(f(n)),'x)'])
end
hold off
lgd = legend;
lgd.NumColumns = 2; % 凡例の列数を指定
プロパティについての詳細は、以下の URL よりヘルプドキュメントをご覧ください。
・Legend 関数ドキュメント
R2017b 以降のバージョンについては、残念ながら、凡例を行列の構成で設定する機能は MATLAB では提供されていません。
代替案として、以下のように、複数の legend オブジェクトを用いて作成する方法が考えられます。
xData = linspace(0,pi);
y1 = sin(xData);
y2 = cos(xData);
y3 = sin(xData.^2);
y4 = cos(xData.^2);
% データの最初の2セットを描画
ph1(1) = plot(xData,y3,'-ko','DisplayName','Y3 Legend Text');
hold on
ph1(2) = plot(xData,y4,'-bs','DisplayName','Y4 Legend Text');
% 最初の凡例を作成
lh1 = legend(ph1,'Location','NorthOutside','Orientation','horizontal');
lh1_position = get(lh1,'Position');
% 軸のプロパティを設定
fontSize = 16;
xlimits = [0,pi];
ylimits = [-1, 1];
xticks = [0, pi/2, pi];
yticks = [-1, 0, 1];
xTickLabels = {'0', 'pi/2', 'pi'};
set(gca,'XLim',xlimits,'YLim',ylimits,'FontSize',fontSize,'XTick',xticks,'YTick',yticks,'xTickLabel',xTickLabels);
% 最初の軸をax1とし、最初の軸の上に2番目の軸(ax2)を作成
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'));
% ax2上に2番目のデータをプロット
ph2(1) = plot(xData,y1,'-rd','DisplayName','Y1 Legend Text','Parent',ax2);
hold on
ph2(2) = plot(xData,y2,'-g^','DisplayName','Y2 Legend Text','Parent',ax2);
% 凡例のフォントが同じになるように軸プロパティを再度設定
set(ax2,'XLim',xlimits,'YLim',ylimits,'FontSize',fontSize,'XTick',xticks,'YTick',yticks);
% 最初の軸と2番目の軸をリンクし、2番目の非表示
linkaxes([ax1 ax2],'xy');
set(ax2,'Color','none','XTick',[],'YTick',[],'Box','off');
% 2番目凡例を1番目の上に作成
lh2 = legend(ax2,ph2,'Orientation','horizontal');
lh2_position = lh1_position;
lh2_position(2) = lh1_position(2)+1.25*lh2_position(4);
set(lh2,'Position',lh2_position);
また、ユーザコミュニティである MATLAB Central / File Exchange には、関連プログラムが公開されています。
1) MATLAB Central : GRIDLEGEND
2) MATLAB Central : COLUMNLEGEND
3) MATLAB Central : FLEXLEGEND
ただし、MATLAB Centralにおいてフリーで公開されているファイルの内容に関しましては、直接プログラム作成者の方にお問い合わせください。
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!