pythonmatplotlibplot

set legend for plot with several lines (in python)


I have several lines plotted in the same figure and I want name this group of lines according to its content. Over those lines I intended yet to plot the average with the errorbar. But two main problem arise:

1) My legend does not appear as I intend (even trying to plot a extra point out of the range of the figure I can't give them a name - workaround)

2) the plot with the average and errorbars is not superposed. Sometimes it is in front and sometimes it is behind the other curves.

What should I do to get it fixed? I could do it in Matlab (same problem for Matlab) But did not find the answer for pythonenter image description here.

This is the part of the plot of my routine:

    UYavg = np.nanmean(UYbvall,0)
    yerr = np.nanstd(UYbvall,0)
    plt.figure()
    for i in range(71):
        plt.plot(LTbvall[i],UYbvall[i],'r-')
    l1 = plt.plot([-2,-1],[1,2],'r-')
    l2 = plt.plot(LTbvall[3],UYavg,'b*-')
    plt.errorbar(LTbvall[2],UYavg, yerr = yerr,ecolor='b')
    plt.xlabel('Tempo (LT)')
    plt.xlim(0,24)
    plt.ylabel('Uy (m/s)')
    plt.title('Vento neutro zonal calculado pelo modelo NWM (BV)')
    plt.legend((l1,l2),('Perfis COPEX','Media'), loc = 'best')

EDIT: the answer must be similar to Multiple lines in a plot or make-custom-legend-in-matplotlib


Solution

  • Well based on another questions (make-custom-legend-in-matplotlib and force-errorbars-to-render-last-with-matplotlib) I got it right. The second error should not happen, I think there may be a bug on zorder option. If I select only the larger number for the error bar, the plot of error bar continues hiden. So I had to set a negative number for the zorder for the lines in the for loop.

    The lines that fix the problems are:

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    for i in range(71):
        ax.plot(LTbvall[i],UXbvall[i],'-',color ='#C0C0C0',label = 'Perfis COPEX',zorder = -32)
    ax.plot(LTbvall[3],UXavg,'b*-', label = u'média')
    ax.errorbar(LTbvall[3],UXavg, yerr = yerr,ecolor='b',zorder = 10)
    #Get artists and labels for legend and chose which ones to display
    handles, labels = ax.get_legend_handles_labels()
    display = (0,71)
    ax.set_xlabel('Tempo (LT)')
    ax.set_xlim(0,24)
    ax.set_ylabel('Ux (m/s)')
    ax.set_title('Vento neutro meridional calculado pelo modelo NWM (BV)')
    ax.legend([handle for i,handle in enumerate(handles) if i in display],
          [label for i,label in enumerate(labels) if i in display], loc = 'best')
    fig.savefig(path[9] + 'Uxbvall_LT_nwm')
    plt.clf() 
    plt.gcf()
    plt.close()
    

    The output is as follows:

    enter image description here