0

I would like to have a function that adds plots to an existing chart when called. Right now my empty plot shows, but called the function never seems to happen as it waits until I close the chart window. The program then ends without reopening the chart window.

import numpy as np
import matplotlib.pyplot as plt
import time

fig, ax = plt.subplots()
plt.show()
def plotting(slope, intercept):

    x_vals = np.array(ax.get_xlim())
    y_vals = intercept + slope * x_vals
    ax.plot(x_vals, y_vals, '-')
    plt.show()

plotting(10,39)
time.sleep(1)
plotting(5,39)

2 Answers 2

3

plt.show() is meant to be called once at the end of the script. It will block until the plotting window is closed.

You may use interactive mode (plt.ion()) and draw the plot at intermediate steps (plt.draw()). To obtain a pause, don't use time.sleep() because it'll let the application sleep literally (possibly leading to freezed windows). Instead, use plt.pause(). At the end, you may turn interactive mode off again (plt.ioff()) and finally call plt.show() in order to let the plot stay open.

import numpy as np
import matplotlib.pyplot as plt

plt.ion()
fig, ax = plt.subplots()

def plotting(slope, intercept):

    x_vals = np.array(ax.get_xlim())
    y_vals = intercept + slope * x_vals
    ax.plot(x_vals, y_vals, '-')
    plt.draw()

plotting(10,39)
plt.pause(1)
plotting(5,39)

plt.ioff()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

2

Send the optional keyword argument block=False to plt.show().

Explanation: the plot window blocks the program from continuing. Sending this argument will allow the program to continue. Notice that if you only use that argument and the program ends, then the plot window is closed. Therefore you might want to call plt.show(block=True) or plt.waitforbuttonpress() at the end of the program.


Personally I would go for adding a block argument for your own function:

def plotting(slope, intercept, block=True):

    x_vals = np.array(ax.get_xlim())
    y_vals = intercept + slope * x_vals
    ax.plot(x_vals, y_vals, '-')
    plt.show(block=block)

plotting(10,39,False)
time.sleep(1)
plotting(5,39)

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.