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

如何将Seaborn图表转换为字节对象而非保存到文件?

问题:如何将Seaborn图表转换为bytes对象而非保存为文件?

我已经掌握了Plotly将图表转为bytes对象的方法,示例代码如下:

import plotly.express as px
import plotly.io as pio

wide_df = px.data.medals_wide()

fig = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"], title="Wide-Form Input, relabelled",
             labels={"value": "count", "variable": "medal"})

# Convert the figure to a bytes object
img_bytes = pio.to_image(fig, format='png')

# Pass the bytes object to the other function
other_function(img_bytes)

但使用Seaborn时,当前代码会将图表保存为文件:

cf_matrix = confusion_matrix([0,1,1], [0,1,0])
ax = sns.heatmap(
        cf_matrix, annot=labels, fmt="", vmin=0, vmax=100
    )

sns_figure = ax.get_figure()

cm_image = sns_figure.savefig('test_image.png')

我尝试用plotly.io的to_image方法转换Seaborn图表:

import plotly.io as pio
img_bytes = pio.to_image(fig_sns, format='png')

却出现错误:

ValueError: The fig parameter must be a dict or Figure. Received value of type <class 'matplotlib.figure.Figure'>: Figure(640x480)

请问如何正确将Seaborn图表转换为字节对象?


解决方法

Seaborn基于Matplotlib实现,因此可以借助Matplotlib的BytesIO对象完成转换,无需保存到本地文件。具体实现步骤如下:

  1. 导入io模块中的BytesIO类
  2. 创建一个BytesIO内存缓冲区对象
  3. 将Seaborn对应的Matplotlib Figure写入缓冲区
  4. 重置缓冲区指针到起始位置,读取字节数据

完整代码示例:

from io import BytesIO
import seaborn as sns
from sklearn.metrics import confusion_matrix

# 生成Seaborn热力图
cf_matrix = confusion_matrix([0,1,1], [0,1,0])
ax = sns.heatmap(cf_matrix, annot=True, fmt="", vmin=0, vmax=100)
sns_figure = ax.get_figure()

# 将图表转为bytes对象
img_buffer = BytesIO()
# 将图表写入缓冲区,指定格式为png
sns_figure.savefig(img_buffer, format='png')
# 重置缓冲区指针到开头,否则读取会得到空数据
img_buffer.seek(0)
# 获取字节数据
img_bytes = img_buffer.getvalue()

# 传递给目标函数使用
other_function(img_bytes)

额外说明:

  • 调用savefig时无需传入文件名,直接传入BytesIO对象即可
  • 可通过savefig的dpi参数调整图片分辨率,比如dpi=300
  • 如果不需要保留Matplotlib Figure对象,可在转换后调用sns_figure.clf()释放内存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28