Pyplot either freezes or does not show in interactive mode

痞子三分冷 提交于 2021-02-11 16:58:44

问题


I am making a script that fetches data every minute and then tries to show that in a matplotlib pyplot. I have three main files: control_cycle.py to control the loop and interact with other functions, api_connect.py(ac) to communicate with server and fetch data and graph_stock.py (gs) with a function to graph the data. So it is important that all time control and waiting is controller by control_cycle.py. However I just can't get the plotting to function properly. I have tried over a dozen solutions like this one, but they either: (A) make the pyplot unclickable/zoomable/greyed-out, (B) keep the rocket icon bouncing in menu bar with no plots or (C) look great but do not update and blocks the entire script.

Code in control_cycle.py:

if __name__ == '__main__':

    try:
        graph_stock = input("Wil je het aandeel plotten (j/n)? ").lower() == "j"

        while True:
            time_data, stock_close = ac.get_data('MSFT')
            if graph_stock:
                gs.graph_stock(time_data, stock_close)
            time.sleep(60)
    except KeyboardInterrupt:
        pass

Relevant code in graph_stock.py which produces freezing option A:

import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import matplotlib.dates as md
import matplotlib.ticker as ticker
import time

def graph_stock(time_data, stock_data):

    fig = plt.figure(num=1, figsize=(12,6)) #control size and set axis

    localtime = time.asctime(time.localtime(time.time())) #To see if it updates
    plt.title("close rates every minute " + localtime)
    plt.plot(time_data,stock_data, '-b.')
    plt.pause(0.05)

If I remove the plt.pause(0.05) and try to use a combination of plt.ion() on top of the file, plt.draw() and fig.canvas.draw() in the function it does not show, option B

Lastly replacing plt.pause(0.05) with plt.show() stops it from updating, option C. plt.show(block=False) gives option B again.

How can I show the plot properly without it freezing, while still being able to update it?

I did not enclose the data-retrieving as the figure looks just as I want it and I thus didn't deem it relevant, please say so if I should include it.

来源:https://stackoverflow.com/questions/60176895/pyplot-either-freezes-or-does-not-show-in-interactive-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!