首页 > 解决方案 > 在 matplotlib 中的 savefig 期间引发 Python 类型错误

问题描述

我有一个 python 脚本,它使用 pandas 数据框和 matplotlib 来创建一些图。以前该脚本运行良好,没有“折旧”或“未来警告”。我没有使用最新的 python、numpy、matplotlib 等,但不到 1 岁,例如:pandas ~0.9、Python 3.7.5。我被迫重新安装 Windows,所以只是做了一个 pip install 来获取我需要的包,所以它们现在都是最新的。但是,对于最新的软件包,当以下代码运行时,我现在得到了一个例外。

发生异常:TypeError 必须是实数,而不是 str"

当调用保存图形的代码时,它被抛出:

fig.savefig(rf'{cfg.output_dir}plots/data_gaps.png', dpi=100, format='png', transparent=True)

但是,当它需要一个int或float时,我看不到该行中的任何内容。我什至尝试将代码简化为: fig.savefig('data_gaps.png')仍然抛出错误,所以我假设它来自于构建无花果时。

    fig, ax = plt.subplots(nrows=int(len(gap_list)), ncols=1, figsize=(12,int(fig_size(gap_list))), sharex=True)
    fig.suptitle('Recording Gaps')

    for ch in gap_list:
        i = gap_list.index(ch)
        resample_s = 4*ch_gap[ch]['rec_rate']
        ylabel = ch + ' (' + ch_gap[ch]['board'] +') - '+ ch_gap[ch]['unit']
        data = df[ch].resample(f'{resample_s}s').mean()
        is_nan = data.isnull()
        # if `ax` is a numpy array then index it, else just use `ax`
        ax_i = ax[i] if isinstance(ax, np.ndarray) else ax
        ax_i.fill_between(data.index, 0, (is_nan*data.max()), color='r', step='mid', linewidth='0', alpha=0.5)
        ax_i.plot(data.index, data, color='b', linestyle='-', marker=',', label=ylabel)
        ax_i.legend(loc='upper left')

fig_size() 是一个函数,它根据 gap_list 列表的大小返回适当的图形高度。我尝试将其转换为 int 并且只是硬编码一个数字,它仍然会引发错误。谁能看到我哪里出错了?

标签: pythonpandasmatplotlib

解决方案


像往常一样,Python 会告诉你为什么它不起作用:

linewidth='0',将宽度从字符串改为int,linewidth=0

我猜以前版本的 matplotlib 会自动为我解决这个问题,而不会引发警告或异常。


推荐阅读