在https://en.wikipedia.org/wiki/Quadratic_equation上显示了一个图形...
它显示二次方y = ax2 + bx + c,分别改变每个系数,而其他系数固定(值a = 1,b = 0,c = 0)
作为一种学习经历,我决定按照以下步骤在Matplotlib中复制这些图:
import numpy as np
import matplotlib.pyplot as plt
import math
#Plot the quadratic function y = ax2 + bx + c
#Varying each coefficient [a, b, c] separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0)
#Iterate these 5 coeficients and plot each line
coefs = [-2, -1, 0, 1, 2]
#set up the plot and 3 subplots (to show the effect of varying each coefficient)
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(18, 6))
#some x values to plot
x = np.linspace(-2, 2, 30)
for idx, val in enumerate([ax1, ax2, ax3]):
for i, v in enumerate(coefs):
a, b, c = 1, 0, 0
if idx == 0:
a = v
elif idx == 1:
b = v
else:
c = v
y = a * (x**2) + (b * x) + c
val.plot(x, y, label="Coeficient is " + str(coefs[i]))
val.axhline(y=0, color='k')
val.axvline(x=0, color='k')
val.grid()
val.legend(loc='lower center')
plt.show()
它工作正常...
但是我是编程的新手,并且我对使用if语句不是最佳选择感到不安。感觉我应该遍历某些东西,而不是使用ifs。
我还可以通过哪些其他方式迭代系数a,b和c来生成3个不同的子图?