■ 過去記事 : matplotlibの凡例(legend)レイアウト関連メモ
matplotlibでプロットするときにlabel="aaa"と書いて、ax.legend() みたいにlegend機能をオンにすると
最初から図にlegendを付けられる
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 101)
y1 = np.sin(x * np.pi)
y2 = np.cos(x * 2 * np.pi) * 0.5
fig = plt.figure()
ax = fig.add_subplot(111)
# labelオプションで凡例に用いる曲線名を指定
ax.plot(x, y1, c="r", label="$\mathrm{sin}(x)$")
ax.plot(x, y2, c="b", label="$0.5 \mathrm{cos}(2x)$")
ax.grid(axis='both')
# 凡例の表示
ax.legend()
labelを最初に付けずに、後から図に付けたくて色々と調べたのでメモ
import matplotlib.collections as mcol
from matplotlib.legend_handler import HandlerLineCollection, HandlerTuple
from matplotlib.lines import Line2D
import numpy as np
t1 = np.arange(0.0, 2.0, 0.1)
t2 = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
# note that plot returns a list of lines. The "l1, = plot" usage
# extracts the first element of the list into l1 using tuple
# unpacking. So l1 is a Line2D instance, not a sequence of lines
l1, = ax.plot(t2, np.exp(-t2))
l2, l3 = ax.plot(t2, np.sin(2 * np.pi * t2), '--o', t1, np.log(1 + t1), '.')
l4, = ax.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 's-.')
ax.legend*1:
ax.legend(['X', 'Y', 'Z'])
ax.text(1.01, 0.5, ifo, ha='left', va='center', transform=ax.transAxes,
fontsize=18)
ax1.set_ylabel(r'$1-3$\,Hz motion [nm/s]', y=-0.1)
ax2.set_ylabel('')
ax1.set_title('Magnitude 7.1 earthquake impact on LIGO')
plot.show()
1行目で2種類のプロットをして、それに対して後付でlegendを付けてる
ax1, ax2 = plot.axesで、それにlegendを適用すればいいっぽい
この記事もメモ
■ 過去記事 : Matplotlib legends in subplot
この方法は自分は上手く行かなかったけどメモ
■ 過去記事 : すでに描画されているグラフに凡例(ラベル)をつける方法について
というか普通に、
ax = plot.gca()
ax.legend(['data1dayo', 'data2 dayo', 'data3 dayo''])
plot.show()
ランキング参加中です
↓クリックしていただけると嬉しいです〜
*1:l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True) ax.set_xlabel('time') ax.set_ylabel('volts') ax.set_title('Damped oscillation') plt.show()