はじめに
matplotlibのax.legend()で表示できる凡例の順を逆にする方法について説明する。
コード&解説
モジュールのインポートなど
バージョン
データの生成
np.random.random(len(x))でランダムデータを作成する。
ax.legend()で凡例を表示
ax.legend()で凡例を表示すると以下のようになる。

プロットは上からC,B,Aの順となっているが、凡例は上からA,B,Cとなっている。
データを動かせないので、凡例を逆順にしたいという気持ちが湧いてくる。
凡例を逆順にして表示
axにプロットしたものから、ax.get_legend_handles_labels()で凡例に関する情報を取得する。handlesはプロットの形で、labelsにはラベル情報が入る。
ax.legend(handles=handles[::-1],labels=labels[::-1])のようにhandlesとlabelsをそれぞれ[::-1]で逆順に設定することで、凡例を逆順にできる。

2つ並べて表示
横に並べて表示すると以下のようになる。

参考

matplotlibの凡例(legend)レイアウト関連メモ - Qiita
凡例の表示、曲線の選択ax.legend()にオプションを何も含めない場合。import matplotlib.pyplot as pltimport numpy as npx = np.l…
コメント