在python中绘图的问题

时间:2017-10-04 14:51:45

标签: python matplotlib

当我运行我的代码时,该图只显示在x = 4的点上。我希望它在整个区间内显示。

from math import exp, pi, sin
import matplotlib.pyplot as plt
for x in range(-4,5):
    f = (exp(-1*(x)**2))*sin(3*pi*(x))
    print(x,"\t", f)
plt.plot(x,f, 'ro', markersize=1)
plt.show()

1 个答案:

答案 0 :(得分:0)

您必须在列表中累积值才能绘制它们:

from math import exp, pi, sin
import matplotlib.pyplot as plt

xs = []
ys = []
for x in range(-4,5):   # or range(-4, 6) if you need to plot a value for 5
    f = (exp(-1*(x)**2))*sin(3*pi*(x))
    print(x,"\t", f)
    xs.append(x)
    ys.append(f)
plt.plot(xs, ys, 'ro', markersize=1)
plt.show()