简体   繁体   中英

Can't save Matplotlib figure correctly when using a function

This is an example of my code to plot and save a figure:

I'm using Python 3.7.4 and 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()

This code saves and displays the plot figure correctly, as follows:

阴谋

But when the plot is built inside a function, the saved picture background will stay white, making the white ticks and labels from the 'dark-background' style invisible, eg:

for

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()

calling the function with qqplot2(brk_data['adjclose'].pct_change(1).fillna(0), save = True) will display the correct plot:

正确的

but will save the figure incorrectly:

不正确

You just need to indent your if clause in the function like this:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM