如何在所有子图上获取标签和轴标题(python)

时间:2018-10-23 09:50:50

标签: python matplotlib plot

我在这里做错了什么?试图通读所有先前对同一问题的答案,但无法弄清楚问题出在哪里,为什么图例等仅出现在最后一个子图上?我可能在这里想不到这很简单。

#Create subplot
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,8));
axes
#parse into own variables
ax11 = axes[0][0]
ax12 = axes[0][1]
ax21 = axes[1][0]
ax22 = axes[1][1]

# Set plot line width
line_width = 1.5

# Plot data
ax11.plot(winter_temps, label='Winter')
plt.legend()
plt.title('Anomaly in temperature during winters 1953-2016')
plt.xlabel('Months')
plt.ylabel('Temperature anomaly (Celsius)')

ax12.plot(spring_temps, label='Spring')
plt.legend()
plt.title('Anomaly in temperature during springs 1953-2016')
plt.xlabel('Months')
plt.ylabel('Temperature anomaly (Celsius)')

ax21.plot(summer_temps, label='Summer')
plt.legend()
plt.title('Anomaly in temperature during summers 1953-2016')
plt.xlabel('Months')
plt.ylabel('Temperature anomaly (Celsius)')

ax22.plot(fall_temps, label='Fall')
plt.legend()
plt.title('Anomaly in temperature during falls 1953-2016')
plt.xlabel('Months')
plt.ylabel('Temperature anomaly (Celsius)')

# Set y-axis limits
ax11.set_ylim(min_temp, max_temp)
ax12.set_ylim(min_temp, max_temp)
ax21.set_ylim(min_temp, max_temp)
ax22.set_ylim(min_temp, max_temp)

# Turn plot grids on
ax11.grid()
ax12.grid()
ax21.grid()
ax22.grid()

输出: Output

这一切也给了我错误:

No handles with labels found to put in legend.

所以事情是我希望每个子图都有图例,轴标题和图标题。

1 个答案:

答案 0 :(得分:1)

如果使用每个子图句柄,则将在每个子图中生成图例的所需结果- 在情节更改为

后,将您的通话更改为plt.legend()
ax11.legend()
ax12.legend()

或更简单/更一般地,只需遍历最后的所有句柄:

for ax in axes.flat:
    ax.legend(loc='best')

编辑:这是一种更全面的解决方案,用于显示两部分的子图构造-不同之处和一致性。

# Plot data
ax11.plot(winter_temps, label='Winter')
ax11.set_title('Anomaly in temperature during winters 1953-2016')

ax12.plot(spring_temps, label='Spring')
ax12.set_title('Anomaly in temperature during springs 1953-2016')

ax21.plot(summer_temps, label='Summer')
ax21.set_title('Anomaly in temperature during summers 1953-2016')

ax22.plot(fall_temps, label='Fall')
ax22.set_title('Anomaly in temperature during falls 1953-2016')

# set up labels, limits, gridlines, legends
for ax in axes.flat:    
    ax.set_xlabel('Months')
    ax.set_ylabel('Temperature anomaly (Celsius)')
    ax.set_ylim(min_temp, max_temp)
    ax.grid('on')
    ax.legend(loc='best')

我还建议您看一下fig.suptitle(),考虑是否在每个子图(“冬季”)中使用简短标题,因为图例已经包含了该标题。最后,检查sharex/sharey的{​​{1}}参数;这样可以避免在所有四个子图上单独设置尺寸,如果在交互模式下滚动,它们会一起移动。