在matplotlib中更改多个子图上的y轴

时间:2017-05-18 17:59:21

标签: python matplotlib plot axes

我对python和matplotlib相当新。我有以下问题:

我想绘制2000多年的六位气候驾驶员。由于每个图表代表不同的驱动程序,我想给每个y轴一个不同的标签,但我不能索引每个子图。请参阅以下代码和后续错误消息:

###Plot MET drivers
fig3 = plt.figure(figsize=(20, 14))

for ii, name_MET in enumerate (["Day_since_start_of_sim", "Min._Temp", "Max._Temp", "Radiation","CO2_(ppm)","DOY"]):
        ax3 = fig3.add_subplot(2,3,ii+1)
        ax3.plot(drivers,'g-',label='2001')
        ax3.set_title(name_MET)
        ax3.set_xlabel('years')
        ax3[1].set_ylabel('Day_since_start_of_simulation')
        ax3[2].set_ylabel('Degrees C')
        ax3[3].set_ylabel('Degrees C')
        ax3[4].set_ylabel('MJ m-2 d-1')
        ax3[5].set_ylabel('ppm')
        ax3[6].set_ylabel('Days')
        ax3.set_xticks(incr_plot_years)
        ax3.set_xticklabels((incr_plot_years/365).astype('S'), rotation = 45)
        ax3.set_xlim(0,ax3.get_xlim()[1])
        ax3.set_ylim(0,ax3.get_ylim()[1])

错误讯息:

    287     ax3.set_title(name_MET)
    288     ax3.set_xlabel('years')
--> 289     ax3[1].set_ylabel('Day_since_start_of_simulation')
    290     ax3[2].set_ylabel('Degrees C')
    291     ax3[3].set_ylabel('Degrees C')

TypeError: 'AxesSubplot' object does not support indexing

任何人都可以帮忙,我如何单独命名每个y轴?这对我有很大的帮助!

谢谢,

2 个答案:

答案 0 :(得分:1)

您尝试索引ax3,但ax3代表一个子情节,而不是整个情节。相反,您应该在其相应的循环迭代上标记每个y轴。试试这个:

names_MET = ["Day_since_start_of_sim", "Min._Temp", "Max._Temp", "Radiation","CO2_(ppm)","DOY"]
ylabels = ['Day_since_start_of_simulation', 'Degrees C', 'Degrees C', 'MJ m-2 d-1', 'ppm', 'Days']

for ii, (name_MET, ylabel) in enumerate(zip(names_MET, ylabels)):
    ax3 = fig3.add_subplot(2,3,ii+1)
    ax3.plot(drivers,'g-',label='2001')
    ax3.set_title(name_MET)
    ax3.set_xlabel('years')
    ax3.set_ylabel(ylabel)
    ax3.set_xticks(incr_plot_years)
    ax3.set_xticklabels((incr_plot_years/365).astype('S'), rotation = 45)
    ax3.set_xlim(0,ax3.get_xlim()[1])
    ax3.set_ylim(0,ax3.get_ylim()[1])

这里的重要好处是您可以为y轴提供自定义标签,而不必使用您在names_MET中定义的值。例如,单位'Degrees C'而不仅仅是'Min._Temp'

答案 1 :(得分:1)

您似乎枚举了您想要在轴上的名称列表,因此您可以在每次迭代中使用当前名称,如下所示:

fig3 = plt.figure(figsize=(20, 14))

names =["Day_since_start_of_sim", "Min._Temp", "Max._Temp", 
        "Radiation","CO2_(ppm)","DAY"]

for ii, name_MET in enumerate (names):
    ax3 = fig3.add_subplot(2,3,ii+1)
    ax3.plot(drivers[ii],'g-',label='2001')# - unclear what drivers is?
    ax3.set_title(name_MET)
    ax3.set_xlabel('years')
    ax3.set_ylabel(name_MET)
    ax3.set_xticks(incr_plot_years) # - unclear
    ax3.set_xticklabels((incr_plot_years/365).astype('S'), rotation = 45)
    ax3.set_xlim(0,ax3.get_xlim()[1])
    ax3.set_ylim(0,ax3.get_ylim()[1])