1

I want to plot a MatPlotLib.PyPlot graph, which is updated over time, and doesn't block program execution. I don't want the user to have to press a key to display the new graph each time it is updated.

I believe that plt.show(block=False) is required for what I want. However, my code does not perform as desired.

Here is my code:

import matplotlib.pyplot as plt
import time

def ShowGraph():
  n = 2
  while True:
    x = [i for i in range(n)]
    y = [i for i in range(n)]
    plt.plot(x, y, 'r-')
    plt.ylim([0, 10])
    plt.xlim([0, 10])
    plt.show(block=False)
    time.sleep(1)
    n += 1

ShowGraph()

This should plot a new graph every second, with the red line getting longer each time. However, all that shows is the graph after the first call to plt.show(). What am I doing wrong?

1 Answer 1

1

When I tried your code as is, it got stuck in an infinite loop. So, I have modified your code slightly to make it work.
Mainly, you need to update your graph using plt.draw() after the first iteration of your loop. plt.show() in non-interactive mode only shows the graph as is, does not update it even with block=False. You still need plt.draw() to update the figure.

import matplotlib.pyplot as plt
import time

def ShowGraph():
    n = 2
    j = 1
    while j <= 10:
        x = [i for i in range(n)]
        y = [i for i in range(n)]
        plt.plot(x, y, 'r-')
        plt.ylim([0, 10])
        plt.xlim([0, 10])
        if j > 1:
            plt.draw()
        else:
            plt.show(block=False)
        time.sleep(1)
        n += 1
        j += 1

ShowGraph()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.