2
votes

The following is code to plot cosine and sine on one pair of axes, from DeCaria's wonderful book Python Programming and Visualization for Scientists. How to I produce the same plot but by plotting cos first, pausing, then plotting sin? Ultimately, I want to plot many functions sequentially and be able to watch for patterns in the family of functions as they emerge.

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,100.0)
y1 = np.cos(2*np.pi*x/50.0)
y2 = np.sin(2*np.pi*x/50.0)
plt.plot(x, y1, 'b-', label = 'Cosine')
plt.plot(x, y2, 'r--', label = 'Sine')
plt.legend(('Cosine', 'Sine'))
plt.show()

Thank you for any help that might be available.

1

1 Answers

1
votes

A simple way to do what you want is to set block = False in your plt.show() command and then update the figure with Figure.canvas.draw() every time you draw a new curve. Here is an example that illustrates how this would work:

import matplotlib.pyplot as plt
import numpy as np

fig,ax = plt.subplots()

x = np.arange(0,100.0)

functions = [
    ('Cosine', np.cos(2*np.pi*x/50.0), 'b-'),
    ('Sine',   np.sin(2*np.pi*x/50.0), 'r--'),
]


plt.show(block = False)


for label, y, style in functions:

    ax.plot(x, y, style, label = label)
    ax.legend()
    fig.canvas.draw()
    input('press <ENTER>')

This code will loop through all the functions that you define in functions (here I used tuples that hold the function name, the y-values, and the plot style) and pause after every update, waiting for keyboard input in the terminal. If you somehow want to only interact with the figure (no terminal input), you will have to start fiddling with matplotlib events. Hope this helps.