Issues with plotting in python

Viewed 48

When I run my code, the plot only shows up in the point x = 4. I want it to show up in the entire interval.

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 Answers

You must to accumulate the values in a list in order to plot them:

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