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

如何将Seaborn与Matplotlib图表保存为HTML文件?

问题解决:Seaborn/Matplotlib图表保存为HTML文件

错误原因

sns.heatmap() 返回的是Matplotlib的 AxesSubplot 对象,该对象没有 write_html() 方法——这个方法是Plotly这类支持交互式HTML输出的可视化库专属的,直接调用自然会触发 AttributeError。

解决方案

方案1:生成嵌入静态图片的HTML

先把Seaborn图表存为图片,再手动生成包含该图片的HTML文件,适合不需要交互的场景。

修改后的代码:

from statistics import correlation
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os

def dynamic_manual_eda(df):
    # 确保templates目录存在
    os.makedirs("templates", exist_ok=True)
    
    # 绘制缺失值热力图
    plt.figure(figsize=(10,6))
    sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis')
    # 保存图表为图片
    plt.savefig("templates/missing_viz.png", bbox_inches='tight')
    plt.close()  # 释放内存
    
    # 生成HTML内容
    html_content = f"""
    <html>
        <body>
            <h2>缺失值热力图</h2>
            <img src="missing_viz.png" alt="Missing Values Heatmap" style="width:100%;">
        </body>
    </html>
    """
    # 写入HTML文件
    with open("templates/missing_viz.html", "w", encoding='utf-8') as f:
        f.write(html_content)

eda_file = pd.read_csv('C:/Users/Churn_bank.csv')
dynamic_manual_eda(eda_file)

方案2:用mpld3生成交互式HTML

mpld3可以把Matplotlib/Seaborn图表转换成带缩放、平移功能的交互式HTML,适合需要交互操作的场景。

步骤:

  1. 先安装依赖:pip install mpld3
  2. 修改代码如下:
from statistics import correlation
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import mpld3
import os

def dynamic_manual_eda(df):
    # 确保templates目录存在
    os.makedirs("templates", exist_ok=True)
    
    # 绘制缺失值热力图
    fig, ax = plt.subplots(figsize=(10,6))
    sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis', ax=ax)
    
    # 转换为交互式HTML并保存
    html_content = mpld3.fig_to_html(fig)
    with open("templates/missing_viz.html", "w", encoding='utf-8') as f:
        f.write(html_content)
    plt.close(fig)  # 释放内存

eda_file = pd.read_csv('C:/Users/Churn_bank.csv')
dynamic_manual_eda(eda_file)

注意事项

  • 方案1是静态HTML,图表以图片形式展示,无法交互;方案2是交互式HTML,保留了图表的操作特性。
  • 代码里加了os.makedirs确保保存目录存在,避免因目录缺失报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:40:45