[英]Create legend click events on multiple matplotlib.pyplot subplots
[英]matplotlib (python) - create single custom legend for multiple plots WITHOUT pyplot
我想在pyqt GUI中的matplotlib(python)中為多個圖創建自定義圖例。 (pyqt建議不要使用pyplot,因此必須使用面向對象的方法)。
多個圖將出現在一個網格中,但是用戶可以定義要顯示多少個圖。 我希望圖例出現在所有圖的右側,因此我不能簡單地為最后繪制的軸創建圖例。 我希望為整個圖形創建圖例,而不僅僅是最后一個軸(類似於pyplot中的plt.figlegend )。
在我在其他地方看到的示例中,這需要參考繪制的線。 同樣,我無法執行此操作,因為用戶可以選擇在圖表上顯示哪些線條,而我寧願圖例始終顯示所有可能的線條,無論它們當前是否顯示。
(請注意,下面的示例代碼使用pyplot,但我的最終版本無法使用)
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
fig = plt.figure()
# Create plots in 2x2 grid
for plot in range(4):
# Create plots
x = np.arange(0, 10, 0.1)
y = np.random.randn(len(x))
y2 = np.random.randn(len(x))
ax = fig.add_subplot(2,2,plot+1)
plt.plot(x, y, label="y")
plt.plot(x, y2, label="y2")
# Create custom legend
blue_line = mlines.Line2D([], [], color='blue',markersize=15, label='Blue line')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Green line')
ax.legend(handles=[blue_line,green_line],bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
如果我將ax.legend更改為:fig.legend(handles = [blue_line,green_line]),則python會產生錯誤:
TypeError:legend()至少接受3個參數(給定2個)
(我猜是因為沒有引用線點)
感謝您提供的任何幫助-我已經看了一個星期了!
您收到的錯誤是因為Figure.legend
要求您將handles
和labels
都傳遞給它。
從文檔:
圖例(句柄,標簽,* args,** kwargs)
在圖中放置圖例。
labels
是字符串序列,handles
是Line2D
或Patch
實例序列。
以下作品:
# Create custom legend
blue_line = mlines.Line2D([], [], color='blue',markersize=15, label='Blue line')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Green line')
handles = [blue_line,green_line]
labels = [h.get_label() for h in handles]
fig.legend(handles=handles, labels=labels)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.