如何将Matplotlib绘制的图表保存为HTML格式?
将Matplotlib图表导出为交互式HTML文件的解决方案
Matplotlib本身不支持直接导出HTML格式,但可以通过第三方库实现,以下两种方案可满足你的需求:
方法1:使用mpld3转换Matplotlib图表为HTML
mpld3能把Matplotlib生成的静态图表转换成带交互功能的HTML文件,步骤如下:
- 安装依赖库:
pip install mpld3
- 修改原有代码,替换PDF保存逻辑:
import mpld3 # 保留原绘图逻辑 fig, ax = plt.subplots(2, constrained_layout = True) for x in new_hpg_groupdf: ax[0].plot(x[1]['iTOW'] , x[1]['ionoEst'] , label=f"{satellite} {x[0][1]}") ax[0].set_ylabel("Iono Estimation (TECU)") ax[0].set_xlabel("Itows (mSec)") ax[0].grid(True) ax[0].legend(fontsize=4 , loc='upper left' , bbox_to_anchor=[1.01, 1.02]) ax[0].set_title('Iono Estimation Output') ax[1].plot(x[1]['iTOW'] , x[1]['ionoEstAcc'] , label=f"{satellite} {x[0][1]}") ax[1].set_ylabel("Iono Accuracy (TECU)") ax[1].set_xlabel("Itows (mSec)") ax[1].grid(True) ax[1].legend(fontsize=4 , loc='upper left' , bbox_to_anchor=[1.01, 1.02]) ax[1].set_title('Iono Estimation Accuracy Output') # 保存为HTML文件 output_file = config["output_dir"] / "report.html" mpld3.save_html(fig, output_file) plt.close()
生成的HTML支持缩放、平移操作,鼠标悬停可查看数据点细节,完全保留你原有的Matplotlib绘图逻辑。
方法2:改用Plotly绘制(原生支持交互式HTML)
如果追求更丰富的交互效果,可以直接使用Plotly绘图,它原生支持导出HTML:
- 安装Plotly:
pip install plotly
- 重写绘图代码:
import plotly.graph_objects as go from plotly.subplots import make_subplots # 创建2行1列的子图 fig = make_subplots(rows=2, cols=1, subplot_titles=('Iono Estimation Output', 'Iono Estimation Accuracy Output')) # 遍历数据添加曲线 for x in new_hpg_groupdf: # 第一张子图:Iono Estimation trace1 = go.Scatter( x=x[1]['iTOW'], y=x[1]['ionoEst'], mode='lines', name=f"{satellite} {x[0][1]}" ) # 第二张子图:Iono Estimation Accuracy trace2 = go.Scatter( x=x[1]['iTOW'], y=x[1]['ionoEstAcc'], mode='lines', name=f"{satellite} {x[0][1]}" ) fig.add_trace(trace1, row=1, col=1) fig.add_trace(trace2, row=2, col=1) # 设置布局参数 fig.update_layout( height=800, width=1000, showlegend=True, legend=dict(font=dict(size=8), x=1.01, y=1) ) # 设置坐标轴标签 fig.update_xaxes(title_text="Itows (mSec)", row=1, col=1) fig.update_yaxes(title_text="Iono Estimation (TECU)", row=1, col=1) fig.update_xaxes(title_text="Itows (mSec)", row=2, col=1) fig.update_yaxes(title_text="Iono Accuracy (TECU)", row=2, col=1) # 显示网格 fig.update_xaxes(showgrid=True) fig.update_yaxes(showgrid=True) # 保存为HTML文件 output_file = config["output_dir"] / "report.html" fig.write_html(output_file)
这种方案的交互性更强,支持图例切换、数据点高亮、精细缩放拖拽等功能,适合需要更优可视化效果的场景。
内容的提问来源于stack exchange,提问作者Kapil
相关产品推荐
相关产品推荐

