MATLABで凡例の表示順序を変更する方法

MATLABで図例の順序を変更するには、legend 関数を使用できます。デフォルトでは、凡例の項目は、描画関数が呼び出された順序と同じ順序で並べられます。ただし、凡例項目の順序を指定することで並べ替えられます。

図例の並び順を変更するサンプルコードを以下に示します。

x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
y3 = tan(x);

plot(x, y1, 'r', 'DisplayName', 'sin(x)');
hold on;
plot(x, y2, 'g', 'DisplayName', 'cos(x)');
plot(x, y3, 'b', 'DisplayName', 'tan(x)');
hold off;

legend('tan(x)', 'cos(x)', 'sin(x)');

上の例では、DisplayNameパラメータによって各曲線に名前を指定しています。次に、legend関数で任意の順番でDisplayNameを指定することで、凡例内の表示順序を変更しています。

コードを実行すると凡例のグラフが生成され、tan(x) の項が 1 番目、cos(x) の項が 2 番目、sin(x) の項が 3 番目に置かれます。

bannerAds