Matplotlib图 - 简化

时间:2017-01-23 23:14:31

标签: python matplotlib

我尝试了几种方法来清理这段代码,但每次都失败了。我只是想清理它。

fig1 = plt.figure()
ax = fig1.add_axes([0.1,0.1,0.8,0.8])
ax.scatter(highForecastTemp, highActTemp)
ax.plot(x, y)
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(x),max(x))
ax.set_title('Forecast vs Actual - High Temperature')
ax.set_xlabel('Forecasted')
ax.set_ylabel('Actual')
plt.show()

fig2 = plt.figure()
ax = fig2.add_axes([0.1,0.1,0.8,0.8])
ax.scatter(lowForecastTemp, lowActTemp)
ax.plot(a, b)
ax.set_xlim(min(a),max(a))
ax.set_ylim(min(a),max(a))
ax.set_title('Forecast vs Actual - Low Temperature')
ax.set_xlabel('Forecasted')
ax.set_ylabel('Actual')
plt.show()

1 个答案:

答案 0 :(得分:1)

编写函数有助于清理:

def plot_forecast(x, y, forecast_temp, act_temp, high_low)
    fig1 = plt.figure()
    ax = fig1.add_axes([0.1,0.1,0.8,0.8])
    ax.scatter(forecast_temp, act_temp)
    ax.plot(x, y)
    ax.set_xlim(min(x),max(x))
    ax.set_ylim(min(x),max(x))
    ax.set_title('Forecast vs Actual - {} Temperature'.format(high_low))
    ax.set_xlabel('Forecasted')
    ax.set_ylabel('Actual')
    plt.show()

plot_forecast(x, y, highForecastTemp, highActTemp, 'High')
plot_forecast(a, b, lowForecastTemp, lowActTemp, 'Low')

现在,您可以使用实际在图之间更改的值调用plot_forecast。您无需复制所有绘图逻辑。