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

folium嵌入mpld3图表报错:matplotlib.dates无_SwitchableDateConverter属性

问题解决思路

错误根因

该错误是mpld3版本与当前matplotlib版本不兼容导致的:旧版mpld3依赖matplotlib内部非公开的_SwitchableDateConverter类,而3.4及以上版本的matplotlib已经移除了这个内部类,因此调用mpld3.fig_to_html时会触发属性不存在的错误。

可行解决方法

方案1:降级matplotlib到兼容版本

如果你的其他代码不依赖高版本matplotlib的特性,该方案操作最简单,直接执行以下命令安装兼容版本即可:

# pip安装
pip install matplotlib==3.3.4

# conda安装
conda install matplotlib=3.3.4

方案2:替换mpld3方案,改用base64嵌入静态图(更稳定,无依赖冲突)

不需要调整现有依赖版本,直接修改getFigure函数实现即可,逻辑是将matplotlib生成的图转为base64编码的png图片,直接嵌入iframe,稳定性远高于mpld3方案,修改后的代码如下:

import io
import base64
import matplotlib.pyplot as plt

def getFigure(state):
    """
    Plot voting trends from a given state
    """
    #Get number of votes
    years = range(1976,2020,4)
    dems = []
    reps =[]
    for year in years:
        result = results[year][state]
        dems.append(result['dem']/1000000)  
        reps.append(result['rep']/1000000) 

    #Plot number of votes    
    fig = plt.figure(figsize=(8,4))
    plt.plot(years,dems,label='Democrat',color='#4f7bff')
    plt.plot(years,reps,label='Republican',color='#ff5b4f')

    plt.title(state,size = 18)
    plt.ticklabel_format(style='plain')
    plt.xlabel('Year',size =14)
    plt.xticks(years)
    plt.ylabel('Votes (millions)',size =14)
    plt.legend(loc =0)

    # 替换mpld3逻辑:转base64嵌入
    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight')
    buf.seek(0)
    img_base64 = base64.b64encode(buf.read()).decode('utf-8')
    buf.close()
    plt.close(fig) # 避免内存泄漏

    html = f'<img src="data:image/png;base64,{img_base64}">'
    iframe = folium.IFrame(html=html,width = 600, height = 300)
    return iframe

方案3:更新mpld3到最新开发版(不推荐)

mpld3正式版已多年未更新,其开发版可能已经修复了该兼容性问题,但稳定性没有保障,仅作为备选方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:54:05