简体   繁体   中英

Adding a second plot to an existing matplotlib chart

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)

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

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)

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