簡體   English   中英

matplotlib(python)-在沒有pyplot的情況下為多個圖創建單個自定義圖例

[英]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.)

在RHS上繪制圖例

如果我將ax.legend更改為:fig.legend(handles = [blue_line,green_line]),則python會產生錯誤:

TypeError:legend()至少接受3個參數(給定2個)

(我猜是因為沒有引用線點)

感謝您提供的任何幫助-我已經看了一個星期了!

您收到的錯誤是因為Figure.legend要求您將handleslabels都傳遞給它。

從文檔:

圖例(句柄,標簽,* args,** kwargs)

在圖中放置圖例。 labels是字符串序列, handlesLine2DPatch實例序列。

以下作品:

# 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM