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

mplfinance绘图传入bbox_inches='tight'报KeyError,如何设置紧凑边距?

mplfinance设置绘图紧凑边距的解决方案

报错原因

bbox_inches是Matplotlib中savefig()方法的专属参数,mplfinance的mpf.plot()接口本身不支持直接传入该参数,因此会触发未识别关键字的报错。

解决方案

分两种使用场景选择对应的设置方法:

场景1:直接显示图表时调整紧凑边距

使用mpf.plot()内置的scale_padding参数控制边距大小,参数值越小边距越紧凑,默认值为1,示例代码如下:

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")
# 调整scale_padding数值实现不同程度的紧凑效果
mpf.plot(df, style='charles', type = 'candle', volume=True, figratio=(12,8), scale_padding=0.1)

场景2:保存图片时实现紧凑边距

如果需要导出图片文件,可通过returnfig=True参数获取Matplotlib的figure对象,再调用原生savefig()方法传入bbox_inches='tight'即可,示例代码如下:

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会返回(figure对象, axes列表)
fig, axlist = mpf.plot(df, style='charles', type = 'candle', volume=True, figratio=(12,8), returnfig=True)
# 调用Matplotlib原生保存方法传入紧凑边距参数
fig.savefig('google_k线.png', bbox_inches='tight')
# 需同步显示图表可添加如下代码
# mpf.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:27:01