twinx() を使用した二次軸: 凡例に追加する方法 質問する

twinx() を使用した二次軸: 凡例に追加する方法 質問する

を使って 2 つの y 軸を持つプロットを作成しましたtwinx()。また、線にラベルを付けて、 で表示したいのですlegend()が、凡例に 1 つの軸のラベルしか表示できません。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

したがって、凡例には最初の軸のラベルのみが表示され、2 番目の軸のラベル「temp」は表示されません。この 3 番目のラベルを凡例に追加するにはどうすればよいですか?

ここに画像の説明を入力してください

ベストアンサー1

次の行を追加すると、2 番目の凡例を簡単に追加できます。

ax2.legend(loc=0)

次のものが得られます:

ここに画像の説明を入力してください

ただし、すべてのラベルを 1 つの凡例に表示したい場合は、次のようにします。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

すると次のようになります:

ここに画像の説明を入力してください

おすすめ記事