简体   繁体   English

将 matplotlib plot 从另一个 function 保存为图像,但不显示 Z32FA6E1B78A06D40284953E6

[英]Saving matplotlib plot from another function as image but without showing the plot

I am writing a school project in Python + Tkinter and I'm trying to make a button, which when clicked saves a plot which is created in other function (createPlot()) but without showing the actual plot. I am writing a school project in Python + Tkinter and I'm trying to make a button, which when clicked saves a plot which is created in other function (createPlot()) but without showing the actual plot. I want to avoid code repetition, therefore, I don't want to just copy the code from the createPlot() function and change the last line.我想避免代码重复,因此,我不想只从 createPlot() function 复制代码并更改最后一行。 Do you have any idea how to do this?你知道怎么做吗? I would appreciate any advice.我会很感激任何建议。 Here is the main part of code:这是代码的主要部分:

def createPlot():
    try:
        plt.style.use('Solarize_Light2')
        plt.plot(analyzeTotalNumOfInfected(),color='y', label='Some Label')
        plt.plot(analyzeNumOfTestsPerDay(),color='r', linestyle='--', label='another Label')
        plt.legend()
        plt.tight_layout
        plt.grid(True)
        fig = plt.gcf()
        fig.canvas.set_window_title('Window title...')
        plt.title('Plot title')
        plt.ylabel('y axis')
        plt.xlabel('x axis')
        plt.show()
    except FileNotFoundError as e:
        messagebox.showerror("Error!", "Lorem Ipsum")

    except Exception as e:
        messagebox.showerror("Error2!", "Lorem Ipsum2")

def savePlot():
    fig = createPlot()
    fig.savefig(os.path.join(sFolder_path,"image.png"))

You can modify your savePlot() method to this so the image names won't override:你可以修改你的 savePlot() 方法,这样图像名称就不会被覆盖:

from datetime import datetime

def savePlot():
    time = datetime.now().ctime().replace(" ", "")
    fig = createPlot()
    fig.savefig(os.path.join(sFolder_path, f"image@{time}.png"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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