Search code examples
pythonmatplotliblegendfillmultiple-axes

How to fill legend background color when plotting with TWO axes?


The issue

I have a plot with 2 y-axes, each corresponding to a set of lines. The solid lines correspond to the left y-axis, and the dashed lines correspond to the right y-axis. I also have a legend and I want it to use only the solid lines as the keys since the dashed lines have the same labels, dependent on their color.

The issue is when I plot a legend for the solid lines, followed by the code for the dashed lines, the grid lines show through the legend. I need to have the grid lines specified for both axes since they won't show up otherwise, and if I move the legend to the dashed lines, it uses the dashed lines as keys instead. I don't want to change my plotting order either.

The code and plot

#Plot
x= np.arange(0,3)
fig,ax = plt.subplots(figsize=(6,6))
#DOD
dod1 = ax.plot(x, ctrl_dod,  color='r',       label='CTRL'  )
dod2 = ax.plot(x, mfkc_dod,  color='#e68a00', label='MFKC'  )
dod3 = ax.plot(x, gses_dod,  color='green',   label='GSES'  )
dod4 = ax.plot(x, gses3_dod, color='blue',    label='GSES-3')
dod5 = ax.plot(x, gses4_dod, color='purple',  label='GSES-4')
dod6 = ax.plot(x, mera_dod,  color='brown',   label='MERRA2')
ax.xaxis.grid(True)
ax.set_ylim([0.02,0.044])
ax.set_yticks(np.arange(0.02,0.045,0.004))
ax.set_xlabel('Month')
ax.set_ylabel('Dust Optical Depth (550 nm)')
ax.set_title('Global Mean DOD and DCM')
legend = ax.legend()
legend.get_frame().set_facecolor('white')

#DCM
ax2  = ax.twinx()
dcm1 = ax2.plot(x, ctrl_dcm*1e6,  color='r',       linestyle='--', label='CTRL'  )
dcm2 = ax2.plot(x, mfkc_dcm*1e6,  color='#e68a00', linestyle='--', label='MFKC'  )
dcm3 = ax2.plot(x, gses_dcm*1e6,  color='green',   linestyle='--', label='GSES'  )
dcm4 = ax2.plot(x, gses3_dcm*1e6, color='blue',    linestyle='--', label='GSES-3')
dcm5 = ax2.plot(x, gses4_dcm*1e6, color='purple',  linestyle='--', label='GSES-4')
dcm6 = ax2.plot(x, mera_dcm*1e6,  color='brown',   linestyle='--', label='MERRA2')
ax2.xaxis.grid(True)
ax2.yaxis.grid(True)
ax2.set_xlabel('Month')
ax2.set_ylabel('Dust Column Mass (mg m-2)')

#Limits
axes = plt.gca()
axes.set_xlim([-0.25,2.25])

#Labels
axes.set_xticks(x)
axes.set_xticklabels(['June','July','August'])

#Save
pylab.savefig('dod+dcm.png')

enter image description here

The question

How can I

a) have the legend keys use solid lines and

b) have the background for the legend opaque white?


Solution

  • You may create the legend for the second axes, but use the handles from the first axes.

    h, l = ax.get_legend_handles_labels()
    legend = ax2.legend(h,l, facecolor="white")