matplotlib 如何在子图中插入图例辅助y轴和twinx [重复]

ahy6op9u  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(142)

此问题已在此处有答案

Secondary axis with twinx(): how to add to legend(11个回答)
上个月关门了。
嗨,我下面所有的代码都可以工作,除了图例。我试图蛮力的东西来,但在每个图例中的实际行不匹配。
在纠正了get_labels_handles之后,下面的代码仍然不正确。下面创建了一个带有4行图例的图形(所以我必须删除一个现有的图例。我认为是secondary_y轴参数导致了我的问题,而这些问题不在我能找到的解决方案中)。(test1,test2,test3)被忽略,图例只显示了列框的列标题的文本。
问题似乎是我有secondary_y轴,然后也使用了一个twinx。我认为使用2个twinx(和移动脊椎)可能是唯一的方法去得到一个正确的图例了。

state = ['a','b','c','d']
city = ['a1','b1','c1','d1']

nrows=2 
ncols=2
i=0
fig,ax = plt.subplots(nrows,ncols,figsize=(20,6*nrows))
    
for row in range(nrows):
    for col in range(ncols): 
        
        state_ = state[i]
        city_ = city[i]

        df_state_approvals_original[[state_]].plot(ax=ax[row,col],label='test1')
        ax2= ax[row,col].twinx()
        ax2.spines['right'].set_position(('outward', 60))

        df_mean_price_state[[state_]].plot(ax=ax[row,col],secondary_y=True,label='Test2')

        df_annual_price_change_city[[city_]].plot(ax=ax2,color='red',ls='--',label = 'Test3')
          
        
        #lns=['Dwelling Approvals (lhs)',city_ + ' annual property price % chng (rhs2)','Mean property price (rhs1)']
        #fig.legend(labels=lns,loc='upper left', bbox_to_anchor=(0,1), bbox_transform=ax[row,col].transAxes)

        lines, labels =ax[row,col].get_legend_handles_labels()
        lines2, labels2=ax2.get_legend_handles_labels()
        
        ax2.legend(lines+lines2, labels + labels2,loc=0)
        
        ax[row,col].set_ylabel("Y1")
        ax[row,col].right_ax.set_ylabel('Y2')
        ax2.set_ylabel("T3")
        ax[row,col].title.set_text('Title')
        
        
        i=i+1
        
fig.subplots_adjust(wspace=0.4, hspace=0.25);
q3aa0525

q3aa05251#

解决方案是改变我的plot参数,然后收集句柄和标签。df.plot(ax=ax)不工作,但ax.plot(df.index,df.values,labels ='test',' color ='red')工作

ax[row,col].plot(df_state_approvals_original.index,df_state_approvals_original[[state_]], label = 'TEST1')
            ax2 = ax[row,col].twinx()
            ax3 = ax[row,col].twinx()
            
            ax2.plot(df_mean_price_state.index,df_mean_price_state[[state_]], label = 'TEST2', color='lightblue')
    
            ax2.spines['right'].set_position(('outward', 60))
        
            ax3.plot(df_annual_price_change_city.index, df_annu_al_price_change_city[[city_]], label = 'TEST3', color='red',ls='--' )

        lines, labels = ax[row,col].get_legend_handles_labels()
        lines2, labels2 = ax2.get_legend_handles_labels()
        lines3, labels3 = ax3.get_legend_handles_labels()
        
        handles = lines + lines2 + lines3
        labels_ = labels + labels2 +labels3
        
        ax3.legend(handles, labels_,loc=0)

相关问题