You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter Notebook单元格中并排展示matplotlib生成的独立图片

无需subplot实现Jupyter单元格内matplotlib独立图片并排的方法

你原有代码输出竖向排列的原因是Jupyter默认会将每个独立生成的matplotlib Figure对象按执行顺序逐行渲染,每个独占一行。以下两种方案都可以在不使用subplot的前提下,实现独立图片横向并排展示:

方法1:HTML内嵌图片实现(兼容性最好)

借助IPython的HTML渲染能力,将生成的独立Figure对象转成base64编码的图片标签,拼接为横向布局后统一展示,无需修改原有绘图逻辑。
完整代码如下:

import matplotlib.pyplot as plt
from IPython.display import display, HTML
import base64
from io import BytesIO

# 辅助函数:将matplotlib Figure转为html img标签
def fig_to_html_img(fig, img_style="display:inline-block;margin:0 10px;"):
    buf = BytesIO()
    # 保存图片到内存,bbox_inches='tight'避免标题被截断
    fig.savefig(buf, format="png", bbox_inches="tight")
    buf.seek(0)
    img_base64 = base64.b64encode(buf.read()).decode("utf-8")
    return f'<img src="data:image/png;base64,{img_base64}" style="{img_style}">'

fig_html_list = []
for i in range(3):
    # 原有绘图逻辑完全不变
    fig, ax = plt.subplots(figsize=[2,2])
    ax.plot()
    ax.set_title('fig ' + str(i))
    # 关闭默认渲染,避免额外输出单张图片
    plt.close(fig)
    fig_html_list.append(fig_to_html_img(fig))

# 拼接所有图片标签并展示
display(HTML("".join(fig_html_list)))

方法2:ipywidgets组件布局实现

如果需要后续对图片做交互调整,可以用ipywidgets的HBox容器包裹图片组件实现横向排布:

import matplotlib.pyplot as plt
from IPython.display import display
from ipywidgets import HBox, Image
from matplotlib.backends.backend_agg import FigureCanvasAgg

# 辅助函数:将matplotlib Figure转为ipywidgets Image组件
def fig_to_widget(fig, width=200, height=200):
    canvas = FigureCanvasAgg(fig)
    canvas.draw()
    buf = canvas.buffer_rgba()
    return Image(value=buf.tobytes(), format="png", width=width, height=height)

fig_widget_list = []
for i in range(3):
    fig, ax = plt.subplots(figsize=[2,2])
    ax.plot()
    ax.set_title('fig ' + str(i))
    plt.close(fig)
    fig_widget_list.append(fig_to_widget(fig))

# 横向展示所有图片组件
display(HBox(fig_widget_list))

两种方案生成的所有图片都是完全独立的Figure对象,没有使用subplot相关的逻辑,符合你的需求。

内容的提问来源于stack exchange,提问作者PBrockmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:30:00