Reputation: 426
I am trying to create a graph of cost function in matplotlib.
Cost function looks like this:
and the graph should look like this:
I have written this code to create the graph in matplotlib:
xs=[]
ys=[]
for x in range(1,11):
y=0.00001*(x**3)-0.003*(x**2)+5*x+1000
xs.append(x)
ys.append(y)
tuples=list(zip(xs,ys))
df=pd.DataFrame(tuples,columns=["x","y"])
df.plot(kind="line",x="x",y="y",figsize=(15,5))
plt.show()
and the graph itself looks like this:
Am I doing anything wrong? How can I get the same distinct shape as in the first graph?
Upvotes: 6
Views: 20546
Reputation: 2763
Use numpy or numpy-like code to make it much easier to write numerical code.
Also, I write 1e-6
here to make sure I use the correct coefficient given by your equation.
import numpy as np
xs = np.linspace(1, 10, 100)
ys = 1e-6*(xs**3) - 0.003*(xs**2) + 5*xs + 1000
plt.plot(xs, ys)
plt.show()
If you want a dataframe, that's ok too:
df = pd.DataFrame({"x": xs, "y": ys})
df.plot(kind="line",x="x",y="y",figsize=(15,5))
plt.show()
Now that the code is simpler, it's easy for you to change the X range and plot the function for another interval - maybe using xs = np.linspace(0, 1500, 100)
.
Upvotes: 8