cJc
cJc

Reputation: 863

How can I plot graphs in Spyder using Matplotlib?

Python 3, Spyder 2.

When I run the following code I want the plot to appear when I enter a float 'a' + Enter. If I then enter a new 'a' I want the graph to update with the new 'a'. But Spyder is not showing the graph until I hit Enter only, which breaks the loop.. I have tried Inline and Automatic, same problem..

import matplotlib.pyplot as plt
L1 = [10.1, 11.2, 12.3, 13.4, 14.5, 13.4, 12.3, 11.1, 10.0]
done = False
while not done:
    a = input("Please enter alpha (between 0 and 1), Enter to exit:")
    if a == "":
        done = True
    else:
        a = float(a)
        L2 = [x * a for x in L1]
        plt.plot(L1)
        plt.plot(L2)

Upvotes: 1

Views: 4227

Answers (1)

Bart
Bart

Reputation: 10277

Difficult to say why the figure won't show; tried adding a plt.show()?

This example runs smoothly on my system. Note that if you actually want to update the graph (instead of appending new lines every time you enter a new a, you need to change the ydata of one of the lines, e.g.:

import matplotlib.pyplot as plt
import numpy as np

L1 = np.array([10.1, 11.2, 12.3, 13.4, 14.5, 13.4, 12.3, 11.1, 10.0])
p1 = plt.plot(L1, color='k')
p2 = plt.plot(L1, color='r', dashes=[4,2])[0]
plt.show()

done = False
while not done:
    a = input("Please enter alpha (between 0 and 1), Enter to exit:")
    if a == "":
        done = True
    else:
        L2 = L1.copy() * float(a)
        p2.set_ydata(L2)

        # Zoom to new data extend
        ax = plt.gca()
        ax.relim()
        ax.autoscale_view()

        # Redraw
        plt.draw()

Upvotes: 1

Related Questions