Mustafa Adel
Mustafa Adel

Reputation: 33

Python code with for loop that did not work

I have run the following code but it showed an empty plot with nothing plotted and I am not able to know the reason Please help

import matplotlib.pyplot as plt
import math
for xx in range(10,100000,1000):
    plt.plot(xx,math.sqrt((.30*(1-.3))/(xx-1)))

Upvotes: 0

Views: 90

Answers (2)

Sheldore
Sheldore

Reputation: 39052

While the other answer solves the issue, you should know that your attempt was not completely wrong. You can use plt.plot to plot individual points in a for loop. However, you will have to specify the marker in that case. This can be done using, let's say, a blue dot using bo as

for xx in range(10,100000,1000):
    plt.plot(xx,math.sqrt((.30*(1-.3))/(xx-1)), 'bo')

Alternatively, in addition to the other answer, you can simply use plt.scatter even for a whole array as following. Note, in this case you will have to use the sqrt module from NumPy as you are performing vectorized operation here which is not possible with math.sqrt

xx = np.arange(10,100000,1000)
plt.scatter(xx,np.sqrt((.30*(1-.3))/(xx-1)), c='green', edgecolor='k')

enter image description here

Upvotes: 1

Michael Silverstein
Michael Silverstein

Reputation: 1843

If you are trying to plot each point individually, try using plt.scatter() like this:

for xx in range(10,100000,1000):
    plt.scatter(xx, math.sqrt((.30*(1-.3))/(xx-1)))

If you're looking to plot a continuous line, you'll want to make your vectors beforehand and then pass them to plt.plot(). I suggest using numpy since np.arrays can handle vectorized data

import numpy as np
# Make x vector
xx = np.arange(10,100000,1000)
# Make y
y = np.sqrt((.30*(1-.3))/(xx-1))
# Plot
plt.plot(xx, y)

Upvotes: 4

Related Questions