簡體   English   中英

matplotlib:子圖中列的通用圖例

[英]matplotlib: common legend to a column in a subplots

假設下面的代碼用於創建我的 plot:

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide xlabels & and tick labels for top plots.
for ax in axs.flat:
    ax.label_outer()

數字:

在此處輸入圖像描述

如何為每一列添加一個通用legend ,例如左列時域右列頻域

在此處輸入圖像描述

下面的代碼基於我對 Jody 在對你的問題的評論中鏈接的問題的回答。 請參考我的其他答案以獲得對以下代碼的詳盡解釋。

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y, label='curve 0 0')
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange', label='curve 0 1')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green', label='curve 1 0')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red', label='curve 1 1')
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide xlabels & and tick labels for top plots.
for ax in axs.flat:
    ax.label_outer()
for col in (0, 1):
    lines_labels = [ax.get_legend_handles_labels() for ax in axs[:,col]]
    lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
    axs[0,col].legend(lines, labels, title=['Time', 'Frequency'][col]+' Domain')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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