この例のような matplotlib errorbar プロットの凡例ピッカーをコーディングしようとしています。凡例のエラーバー/データポイントをクリックして、軸の表示を切り替えられるようにしたいと考えています。問題は、 によって返される凡例オブジェクトに、plt.legend()
凡例の作成に使用されたアーティストに関するデータが含まれていないことです。もし私が例えば。行う:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(0,10,100)
y = np.sin(x) + np.random.rand(100)
yerr = np.random.rand(100)
erbpl1 = ax.errorbar(x, y, yerr=yerr, fmt='o', label='A')
erbpl2 = ax.errorbar(x, 0.02*y, yerr=yerr, fmt='o', label='B')
leg = ax.legend()
leg
ここからオブジェクトを使用して伝説のアーティストにアクセスすることは不可能のようです。通常、これはより単純な凡例で行うことができます。
plt.plot(x, y, label='whatever')
leg = plt.legend()
proxy_lines = leg.get_lines()
凡例で使用される Line2D オブジェクトを提供します。ただし、エラーバー プロットではleg.get_lines()
、空のリストが返されます。オブジェクト (データ ポイント、エラーバー エンド キャップ、エラーバー ラインを含む) をplt.errorbar
返すため、このような方法は理にかなっています。matplotlib.container.ErrorbarContainer
凡例には同様のデータ コンテナーがあると思いますが、これはわかりません。私が管理できる最も近いleg.legendHandles
ものは、エラーバーの線を指すものでしたが、データ ポイントやエンド キャップは指していませんでした。凡例を選択できる場合は、辞書を使用してそれらを元のプロットにマップし、次の関数を使用してエラーバーのオン/オフを切り替えることができます。
def toggle_errorbars(erb_pl):
points, caps, bars = erb_pl
vis = bars[0].get_visible()
for line in caps:
line.set_visible(not vis)
for bar in bars:
bar.set_visible(not vis)
return vis
def onpick(event):
# on the pick event, find the orig line corresponding to the
# legend proxy line, and toggle the visibility
legline = event.artist
origline = lined[legline]
vis = toggle_errorbars(origline)
## Change the alpha on the line in the legend so we can see what lines
## have been toggled
if vis:
legline.set_alpha(.2)
else:
legline.set_alpha(1.)
fig.canvas.draw()
私の質問は、エラーバー/その他の複雑な凡例でイベントピッキングを実行できる回避策はありますか??