ryhn
ryhn

Reputation: 96

how to attach point of plot in for loop without using linspace?

I needed to see the image of a sequence, that's why I chose Python, I got in trouble along the way, that I do not use np.linspace , so the points in the loop are not connected, but I needed to points get connected like they do in np.linspace like they are in a line, but I have no idea how to implement this particular sequence.

the sequence :

$${a_n} = 1 + \sum_{n=1}^{\infty}\frac{1}{n!}$$
= 2 + 1/2! + 1/3! +...+1/n!

y = 1
fac = 1
for n in range(80) :
    fac = fac * (n+1)
    y = y +  1 / fac
    plt.plot(n , y , alpha = 0.5 , color = 'red' , linestyle = 'solid' , 
                linewidth = 2 , marker = '.' , markersize = 2 ,
                markerfacecolor = 'blue' , markeredgecolor = 'blue' )

plt.ylim([-1,4])
plt.savefig('Ascending Highly bounded sequence convergence.png')

plt.clf() #clear figure

the result : enter image description here

Any help is appreciated.

Upvotes: 0

Views: 194

Answers (1)

M472
M472

Reputation: 330

The reason why you don't see a line connecting the points is that you call the plot function for every point. Because of this, matplotlib plots lots of single points with no connections in between.

To get a line between the points you have to call the plot function with a collection of data points.

from matplotlib import pyplot as plt

X = range(80)
Y = []

y = 1
fac = 1
for n in X:
    fac = fac * (n+1)
    y = y +  1 / fac
    Y.append(y)
    
plt.plot(X, Y, alpha = 0.5 , color = 'red' , linestyle = 'solid' , 
            linewidth = 2 , marker = '.' , markersize = 2 ,
            markerfacecolor = 'blue' , markeredgecolor = 'blue' )

plt.ylim([-1,4])
plt.savefig('Ascending Highly bounded sequence convergence.png')

plt.clf() #clear figure

Upvotes: 1

Related Questions