首页 > 解决方案 > 在 Python for 循环中,如何为绘图创建图例?

问题描述

我已经成功创建了四个子图和两个具有双 y 轴特征的子图,如下所示。每个子图都有许多不同的图。我想添加一个传奇。但是,我不能用代码来做到这一点。该图如下:

在此处输入图像描述

我的代码如下:

fig, axs = plt.subplots(2,2,figsize=(17,10))
fig.legend(loc="center right", fontsize=13,fancybox=True, framealpha=1, shadow=True, borderpad=1)    
plt.rc('font',family='Times New Roman')
.
.
for i,j in zip(IV_start_index,IV_start_index[1:]):  # This is simple code to access present and next element in a list    
    axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
    axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
    .  
    .  
    plt.suptitle('A NIST Module %s power loss analysis'%(module_allData_df['Time'].loc[i].strftime('%Y-%m-%d')),fontsize=18) # 
    plt.savefig('All_day_power_loss')

输出是:

No handles with labels found to put in legend.

你能帮我更正我的代码吗?

更正:我确实更改了代码,如下所示。

for i,j in zip(IV_start_index,IV_start_index[1:]):  # This is simple code to access present and next element in a list    
        axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
        axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
        axs[0][0].legend()

它创造了许多传说。输出图如下:

在此处输入图像描述

标签: pythonpython-3.xmatplotlib

解决方案


经过一系列的跟踪,我对我的代码执行了以下操作:

for i,j in zip(IV_start_index,IV_start_index[1:]):  # This is simple code to access present and next element in a list    
    axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs')
    axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd')
    axs[0][0].legend(['Theoretical','Actual'])
    .
    .

我的输出是:

在此处输入图像描述


推荐阅读