我可以使用循环或列表来减少此图的代码吗?

时间:2014-05-14 20:41:47

标签: python loops for-loop

我在一张图上绘制了一些线条,我觉得我错过了一个非常简单的循环,或者会让代码更高效,更容易阅读的东西。

我的一个例子是:

alphaline = .4
polydegree = 3

#first iteration
xg1 = np.array(df1.query('wealb == "g"')['income'])
yg1 = np.array(df1.query('wealb == "g"')['cont'])
coefg1 = np.polyfit(xg1, yg1,polydegree)
polyg1 = np.poly1d(coefg1)
ysg1 = polyg1(xg1)
ax5.plot(xg1, ysg1, color="#5FB404", label="1", alpha=alphaline)

#second iteration
xg2 = np.array(df2.query('wealb == "g"')['income'])
yg2 = np.array(df2.query('wealb == "g"')['cont'])
coefg2 = np.polyfit(xg2, yg2, polydegree)
polyg2 = np.poly1d(coefg2)
ysg2 = polyg2(xg2)
ax5.plot(xg2, ysg2, color="#31B404", label="2", alpha=alphaline)

#third iteration
xg3 = np.array(df3.query('wealb == "g"')['income'])
yg3 = np.array(df3.query('wealb == "g"')['cont'])
coefg3 = np.polyfit(xg3, yg3, polydegree)
polyg3 = np.poly1d(coefg3)
ysg3 = polyg3(xg3)
ax5.plot(xg3, ysg3, color="#088A08", label="3", alpha=alphaline)
lg1 = plt.legend(title="Children in College")

我觉得某种for i in range(3)会有所帮助,但我仍然是python的新手,并且无法真正弄清楚如何实现。我想我可以为颜色设置某种数组,然后循环遍历所有内容。

我也一直在玩

for i in range(len(x)):
  plt.figure()
  plt.plot(x[i],y[i])

来自Use a loop to plot n charts Python

我现在的尝试看起来像是:

colours = ['r','g','b']
for i in range(3):
    xg[i] = np.array(df[i].query('wealb == "g"')['income'])
    yg[i] = np.array(df[i].query('wealb == "g"')['cont'])
    coefg[i] = np.polyfit(xg[i], yg[i],polydegree)
    polyg[i] = np.poly1d(coefg[i])
    ysg[i] = polyg1(xg[i])
    ax5.plot(xg[i], ysg[i], color=colours[i], label=str[i], alpha=alphaline)

0 个答案:

没有答案