問題-3Dアレイ
質問:2012年11月、2013年10月
import numpy as np
a = np.random.random((2, 100, 4))
b = np.random.random((2, 100, 4))
c = np.random.random((2, 100, 4))
解決策-独自性を決定する
私の場合_nolegend_
(bliとDSM)は機能せず、機能しませんlabel if i==0
。 ecatmurの答えはget_legend_handles_labels
、凡例を使用して縮小しcollections.OrderedDict
ます。 Fonsは、これがインポートなしで可能であることを示しています。
これらの答えに沿って、私はdict
ユニークなラベルに使用することをお勧めします。
# Step-by-step
ax = plt.gca() # Get the axes you need
a = ax.get_legend_handles_labels() # a = [(h1 ... h2) (l1 ... l2)] non unique
b = {l:h for h,l in zip(*a)} # b = {l1:h1, l2:h2} unique
c = [*zip(*b.items())] # c = [(l1 l2) (h1 h2)]
d = c[::-1] # d = [(h1 h2) (l1 l2)]
plt.legend(*d)
または
plt.legend(*[*zip(*{l:h for h,l in zip(*ax.get_legend_handles_labels())}.items())][::-1])
Matthew Bourqueのソリューション よりも、読みにくく、記憶に残るものではないかもしれません。コードゴルフへようこそ。
例
import numpy as np
a = np.random.random((2, 100, 4))
b = np.random.random((2, 100, 4))
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.plot(*a, 'C0', label='a')
ax.plot(*b, 'C1', label='b')
ax.legend(*[*zip(*{l:h for h,l in zip(*ax.get_legend_handles_labels())}.items())][::-1])
# ax.legend() # Old, ^ New
plt.show()