如何使用Matplotlib在Spyder中绘制图形?

时间:2016-05-30 09:30:12

标签: matplotlib while-loop spyder

Python 3,Spyder 2.

当我运行以下代码时,我希望在输入浮动'a'+ Enter时显示绘图。如果我然后输入一个新的'a',我希望图表用新的'a'更新。但Spyder没有显示图表,直到我点击Enter,这打破了循环..我试过内联和自动,同样的问题..

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)

1 个答案:

答案 0 :(得分:1)

很难说为什么这个数字不会显示出来;尝试添加plt.show()

此示例在我的系统上顺利运行。请注意,如果您确实要更新图表(而不是每次输入新的a时附加新行,则需要更改其中一行的ydata,例如:

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