I am trying to graph a simple parabola in matplotlib
and I am confused as to how I am supposed to plot points on the parabola. So far, this is what I have:
import matplotlib.pyplot as plt
a=[]
b=[]
y=0
x=-50
while x in range(-50,50,1):
y=x^2+2*x+2
a=[x]
b=[y]
fig= plt.figure()
axes=fig.add_subplot(111)
axes.plot(a,b)
plt.show()
x= x+1
This should do:
This is your approach with as few changes as possible to make it work (because it's clear that you're a beginner and this is a learning exercise). The changes I made were:
Moved the
plt.figure
, and other plotting statements out of the loop. The loop now gives you the data to plot, and then you plot it once the loop is finished.Changed
x^2
tox**2
.Changed
while
tofor
in your main loop control statement.Commented out a few lines that weren't doing anything. They all had the same source of error (or non-utility, really): in the for loop,
x
is set in the loop control line and theny
is calculated directly, so you don't need to give them initial values or incrementx
, though you would have had to do these steps for a while loop.Here the code:
Adjust your third to last line to:
Adding the '
r-^
' will add red triangular points to the graph. Alternatively, you can use 'b-o
'.Note: You should include the quotes.
For different colors you can use 'b' - blue; 'g' - green; 'r' - red; 'c' - cyan; 'm' - magenta; 'y' - yellow; 'k' - black; 'w' - white
The - in the '
r-^
' or 'b-o
' will create the line joining the triangles or circles respectively. That is, without the dash, you will end up with a scatter plot.Alternatively, there is command ....
scatter(x,y)
which would be equivalent to 'r ^
' and 'b o
'