两个 Matplotlib 子图共用图例

Matplotlib 两个子图怎样共用一个图例?

Matplotlib 3.8.4 中用 fig.legend(handles=handles, loc="outside lower center", ncols=2),可在两个子图下方放一个共用图例。

本文目录

发布与实测日期:2026年11月20日。

怎样修改代码才能得到这个结果?

为每条系列保留一个绘图对象句柄,再传入 Figure.legend。layout="constrained" 会为图外位置预留空间。修改后的各子图不再调用 ax.legend。只有两个子图的颜色、点形和系列含义一致时,才能共用这组图例。 我把每条线的句柄各留一个,共用图例时就能直接取用。

本文使用模拟演示数据

原始输出: 两个面板分别重复 Control 和 Comparison 图例。
查看原尺寸图片
原始输出. 两个面板分别重复 Control 和 Comparison 图例。
结果输出: 前图在每个子图中重复 Control 和 Comparison;后图在底部只保留一组两列图例。第二面板各系列增加一个响应单位,共用图例不会合并数据。
查看原尺寸图片
结果输出. 前图在每个子图中重复 Control 和 Comparison;后图在底部只保留一组两列图例。第二面板各系列增加一个响应单位,共用图例不会合并数据。

实际输出有哪些变化?

前图在每个子图中重复 Control 和 Comparison;后图在底部只保留一组两列图例。第二面板各系列增加一个响应单位,共用图例不会合并数据。

timeresponse
12.0
24.0
33.0
46.0
55.0
68.0

表格显示全部输入行。 (6)

使用这个设置前还要检查什么?

本例运行于 Matplotlib 3.8.4。子图使用不同编码时,收集并标注各面板所需的全部句柄。

怎样复现图表并下载文件?

在可写目录运行 python example.py。实际版本为 Python 3.12.4、Matplotlib 3.8.4、NumPy 1.26.4;脚本在自身所在目录生成 data.csv、before.png、after.png、after.pdf。

下面是本文用到的代码、数据和结果文件。你可以下载代码跟着操作,也可以打开结果文件,对照自己运行后的结果。

  • example.py可以在电脑上运行的完整示例代码。
  • data.csv本例使用的输入数据,可作为表格打开。
  • before.png修改前的图,用来比较。
  • after.png按本文设置生成的结果图。
  • after.pdfPDF 格式的结果图,方便查看和排版。
  • 使用许可 · LICENSE.txt说明代码、数据和图表的使用条件,并附来源及字体许可。
文件校验
  • hashes.json用于核对下载文件是否完整的校验值。

完整 Python 代码

# Original Bopbun example, CC0-1.0. See LICENSE.txt for font/software notices.
# Tested: Python 3.12.4, Matplotlib 3.8.4, NumPy 1.26.4.
from pathlib import Path
import csv
import json
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import colors, dates
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.backends.backend_agg import FigureCanvasAgg
from datetime import datetime, timedelta
from textwrap import fill

OUT = Path(__file__).resolve().parent
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11,
    "axes.spines.top": False, "axes.spines.right": False,
    "pdf.fonttype": 42, "figure.dpi": 120, "savefig.dpi": 160})

def data_file(header, rows):
    with (OUT / "data.csv").open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f); w.writerow(header); w.writerows(rows)

def canvas():
    return plt.subplots(figsize=(7.2, 4.5), layout="constrained")

def line_data():
    x = np.arange(1, 7)
    y = np.array([2., 4., 3., 6., 5., 8.])
    data_file(["time", "response"], zip(x, y))
    return x, y

def matrix_data():
    z = np.array([[1., 3., 5., 7.], [2., 4., 6., 8.], [0., 2., 4., 6.]])
    data_file(["row", "column", "value"], ((i,j,z[i,j]) for i,j in np.ndindex(z.shape)))
    return z


def make(fixed):
    x,y = line_data()
    fig,axs = plt.subplots(1,2,figsize=(8,4.5),layout="constrained",sharey=True)
    handles = []
    for i,ax in enumerate(axs):
        a, = ax.plot(x,y+i,label="Control",marker="o")
        b, = ax.plot(x,y+2+i,label="Comparison",marker="s")
        handles = [a,b]
        ax.set(title=f"Panel {i+1}",xlabel="Time (h)")
        if not fixed: ax.legend(loc="upper left")
    axs[0].set_ylabel("Response (a.u.)")
    if fixed: fig.legend(handles=handles,loc="outside lower center",ncols=2)
    return fig
TRANSPARENT = False
MULTIPAGE = False
RASTER = False

if __name__ == "__main__":
    before = make(False)
    after = make(True)
    before.savefig(OUT / "before.png")
    after.savefig(OUT / "after.png", transparent=TRANSPARENT)
    after.savefig(OUT / "after.pdf", transparent=TRANSPARENT,
        metadata={"CreationDate":None,"ModDate":None})
    if MULTIPAGE:
        with PdfPages(OUT / "pages.pdf",metadata={"CreationDate":None,"ModDate":None}) as pdf:
            pdf.savefig(before); pdf.savefig(after)
    if RASTER:
        before.savefig(OUT / "vector.pdf", metadata={"CreationDate":None,"ModDate":None})
    # Draw at the screen renderer before checking label and legend bounds.
    FigureCanvasAgg(after)
    after.canvas.draw()
    renderer=after.canvas.get_renderer()
    checks={"axes":len(after.axes),"text_outside_canvas":[],
        "axes_limits":[{"x":list(ax.get_xlim()),"y":list(ax.get_ylim())} for ax in after.axes]}
    for ax in after.axes:
        xt=[label for value,label in zip(ax.get_xticks(),ax.get_xticklabels()) if min(ax.get_xlim())<=value<=max(ax.get_xlim())]
        yt=[label for value,label in zip(ax.get_yticks(),ax.get_yticklabels()) if min(ax.get_ylim())<=value<=max(ax.get_ylim())]
        for txt in [ax.title,ax.xaxis.label,ax.yaxis.label,*xt,*yt,*ax.texts]:
            if txt.get_visible() and txt.get_text():
                b=txt.get_window_extent(renderer)
                if b.x0 < -1 or b.y0 < -1 or b.x1 > after.bbox.width+1 or b.y1 > after.bbox.height+1:
                    checks["text_outside_canvas"].append(txt.get_text())
    for legend in [*after.legends,*(ax.get_legend() for ax in after.axes if ax.get_legend())]:
        b=legend.get_window_extent(renderer)
        assert b.x0>=0 and b.y0>=0 and b.x1<=after.bbox.width and b.y1<=after.bbox.height
    print(json.dumps(checks,allow_nan=False))
    plt.close("all")

来源与商用许可分别是什么?

原创代码与数据采用 CC0-1.0。图表使用 DejaVu Sans,字体许可单独保留。Matplotlib、NumPy 调用本机已安装依赖,不随下载包分发。

历史讨论。

相关问题应该查看哪篇解答?

科研图表问题集合