【问题标题】:Can't save Matplotlib figure correctly when using a function使用函数时无法正确保存 Matplotlib 图
【发布时间】:2019-11-14 17:49:51
【问题描述】:

这是我绘制和保存图形的代码示例:

我正在使用 Python 3.7.4 和 matplotlib==3.0.3。

import matplotlib.pyplot as plt
import pandas as pd
from yahoo_fin import stock_info
import statsmodels.api as sm

brk_data = stock_info.get_data("BRK-A")

with plt.style.context('dark_background'):

    fig, ax = plt.subplots(figsize=(16, 9))
    sm.qqplot(brk_data['adjclose'].pct_change(1).fillna(0), fit=True, line='45', ax=ax)
    plt.title('QQ Plot', fontsize = 16)
    ax.axvline(0, c  = 'w', linestyle = "--", alpha = 0.5)
    ax.grid(True,linewidth=0.30)
    ax.set_xlim(4,-4)
    ax.set_ylim(5,-5)

    plt.savefig('qqplot.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
    plt.show()
    plt.close()

此代码正确保存并显示绘图图形,如下:

但是当绘图构建在函数内部时,保存的图片背景将保持白色,使“dark-background”样式中的白色刻度和标签不可见,例如:

def qqplot2(pct, save = False):

    with plt.style.context('dark_background'):

        fig, ax = plt.subplots(figsize=(16, 9))
        sm.qqplot(pct, fit=True, line='45', ax=ax)
        plt.title('QQ Plot', fontsize = 16)
        ax.axvline(0, c  = 'w', linestyle = "--", alpha = 0.5)
        ax.grid(True,linewidth=0.30)
        ax.set_xlim(4,-4)
        ax.set_ylim(5,-5)


    if save == True:

        plt.savefig('qqplot2.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
        plt.show()
        plt.close()

    else:

        plt.show()

使用qqplot2(brk_data['adjclose'].pct_change(1).fillna(0), save = True) 调用函数将显示正确的绘图:

但会错误地保存图:

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    你只需要像这样在函数中缩进你的 if 子句:

    def qqplot2(pct, save = False):
    
        with plt.style.context('dark_background'):
    
            fig, ax = plt.subplots(figsize=(16, 9))
            sm.qqplot(pct, fit=True, line='45', ax=ax)
            plt.title('QQ Plot', fontsize = 16)
            ax.axvline(0, c  = 'w', linestyle = "--", alpha = 0.5)
            ax.grid(True,linewidth=0.30)
            ax.set_xlim(4,-4)
            ax.set_ylim(5,-5)
    
    
            if save == True:
    
                plt.savefig('qqplot2.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
                plt.show()
                plt.close()
    
            else:
    
                plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-12
      • 2013-07-26
      • 2021-05-04
      • 2019-12-28
      • 2015-04-23
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多