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

mplfinance使用savefig保存图表时调整边距、修复标题遮挡及添加副标题方法

解决方案

边距调整与标题防遮挡

你可以不用完全依赖tight_layout参数,mplfinance内置了更灵活的边距控制参数scale_padding,搭配标题偏移设置即可实现左右紧凑、标题正常显示的效果:

from pandas_datareader import data as web
import pandas as pd
import mplfinance as mpf

df = web.DataReader('goog','yahoo', start="2021-07-3", end="2021-09-12")

# 配置标题向上偏移,避免和图表内容重叠
title_config = {'title': 'Google 股价走势', 'y': 1.02}
mpf.plot(df, 
         style='charles', 
         type='candle', 
         volume=True, 
         figratio=(12,8),
         scale_padding=0.3, # 数值越小边距越紧凑,0.2-0.4区间即可满足左右紧凑的需求
         title=title_config,
         savefig='testimage.jpg')

如果你坚持要使用tight_layout,可以通过rect参数限制其调整范围,预留顶部标题空间:

mpf.plot(df, 
         style='charles', 
         type='candle', 
         volume=True, 
         figratio=(12,8),
         title='Google 股价走势',
         tight_layout={'rect': [0, 0, 1, 0.95]}, # 仅在画布0-95%高度范围内做紧凑适配,顶部5%留作标题区域
         savefig='testimage.jpg')

添加副标题

mplfinance原生不直接支持副标题,你可以通过returnfig参数拿到底层matplotlib的画布对象,手动添加副标题:

from pandas_datareader import data as web
import pandas as pd
import mplfinance as mpf

df = web.DataReader('goog','yahoo', start="2021-07-3", end="2021-09-12")

# returnfig=True会返回画布对象和轴列表,方便自定义修改
fig, axlist = mpf.plot(df, 
                       style='charles', 
                       type='candle', 
                       volume=True, 
                       figratio=(12,8),
                       scale_padding=0.3,
                       returnfig=True)

# 添加主标题和副标题
fig.suptitle('Google 股价走势', fontsize=16, y=0.98)
fig.text(0.5, 0.93, '2021年7月-9月 日线K线图', ha='center', fontsize=12, color='gray')

# 保存时自动适配内容边界,避免内容裁切
fig.savefig('testimage.jpg', bbox_inches='tight')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:15:03