Knowlesie
Knowlesie

Reputation: 11

Not sure why I a getting an error with Matplotlib.PyPlot

I am writing some code that allows users to enter 2 variables, and then the program is supposed to be able to plot the path of a projectile based on the variables.

I am doing this in Python, using matplotlib.pyplot as my method of plotting graphs. Here is the code:

import math
import matplotlib.pyplot as plt
#Do Maths and stuff
g = 9.81 #Gravitational Constant
r = int(input("Enter angle of Projectile's launch:: "))
u = int(input("Enter intial velocity of projectile: "))
x = 0

while x <= 90:
   y = x * math.tan(r) - (g*(x*x)) / (2*(u*u)*(math.cos(r)*math.cos(r))
   plt.plot(x,y)
   plt.show()

But when I run this, it says that

plt.plot(x,y) 

Is an invalid syntax. Does anyone know why this is?

Thanks

Upvotes: 0

Views: 53

Answers (2)

Mahdi
Mahdi

Reputation: 3238

In addition to what lbellomo mentioned, you're missing one parenthesis at the end of y definition. More importantly, you never change the value of x within the loop, so while loop doesn't stop.

Look at the following code; I think it's a better practice to collect data then plot them.

import math
import matplotlib.pyplot as plt
#Do Maths and stuff
g = 9.81 #Gravitational Constant
r = int(input("Enter angle of Projectile's launch: "))
u = int(input("Enter intial velocity of projectile: "))
x = 0

xdata=[]
ydata=[]
while x <= 10:
    y = x * math.tan(r) - (g/2)*(x/(u*math.cos(r)))**2
    xdata.append(x)
    ydata.append(y)
    x+=1
plt.plot(xdata,ydata,'-ok')
plt.show() 

This is the picture when velocity and angle are 2 and 45, respectively:

enter image description here

Suggestion: Tell people what are the units for angle and velocity (Physics thingy!).

Final thoughts: I strongly recommend using numpy and defining a function:

import numpy as np
import matplotlib.pyplot as plt

def projectile(x,v,t):
    """
    x: x values (m)
    v: initial speed (m/s)
    t: launch angle (radian)
    """
    g=9.8 #Gravitational Constant
    y=x * np.tan(t) - (g/2)*(x/(v*np.cos(t)))**2
    return y

r = int(input("Enter angle of Projectile's launch: "))
u = int(input("Enter intial velocity of projectile: "))

xdata = np.linspace(0,10,10)
ydata = projectile(xdata,u,r)
plt.plot(xdata,ydata,'-ok')
plt.show()

Upvotes: 3

Lucas
Lucas

Reputation: 7341

You have 3 spaces instead of 4 inside the while.

Correct indentation:

while x <= 90:
    y = x * math.tan(r) - (g*(x*x)) / (2*(u*u)*(math.cos(r)*math.cos(r))
    plt.plot(x,y)
    plt.show()

Remember that in python the indentation is VERY important.

Some suggestions:

Do not change the value of x, it will never leave the while.

Surely you would like to take the plt.show() out of the while, to plot all the points together.

Upvotes: 1

Related Questions