Labelcolor of legend per axis

Hello,

how to i set the label text color to the color of the axis label, please? So it is possible to identify the corresponding y axis by the text of the legend label.

bytelinker

import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,100,0.5)
y1=2*x+20
y2=3*x+30
y3=-4*x+340

fig, ax1 = plt.subplots(figsize=(1.5*5,1.5*3))

ax2=ax1.twinx()
ax3=ax1.twinx()

ax1.ticklabel_format(useOffset=False, style='plain')

ax1.set_title('3 axes plot')

text_color_ax1='blue'
text_color_ax2='red'
text_color_ax3='green'


ax1.set_xlabel('x axis')
ax1.set_ylabel('y1 axis', color=text_color_ax1)
ax2.set_ylabel('y2 axis', color=text_color_ax2)
ax3.set_ylabel('y3 axis', color=text_color_ax3)


ax1.set_ylim(0,400)
ax2.set_ylim(0,400)
ax3.set_ylim(0,400)

ax3.spines["right"].set_position(("axes", 1.15))


ax1.plot(x,y1,  label=f'plot 01 01, textcolor should be {text_color_ax1}', color='lawngreen')
ax1.plot(x,y2,  label=f'plot 01 02, textcolor should be {text_color_ax1}', color='peru')
ax2.plot(x,y3,  label=f'plot 02 01, textcolor should be {text_color_ax2}', color='crimson')
ax3.plot(x,y3*2,label=f'plot 03 01, textcolor should be {text_color_ax3}', color='orange')


lines=[]
labels=[]
for i in range(0,len(fig.get_axes())):
    lines_ax, labels_ax=fig.axes[i].get_legend_handles_labels()
    lines+=lines_ax
    labels+=labels_ax
    
ax1.legend(lines, labels, loc='upper center', bbox_to_anchor=(0.5, -0.25),\
          fancybox=True, shadow=False, ncol=2,fontsize=10)

plt.tight_layout()

Since Matplotlib 3.3 you can do legend(..., labelcolor='linecolor').

I can insert

ax1.legend(labelcolor=text_color_ax1)
ax2.legend(labelcolor=text_color_ax2)
ax3.legend(labelcolor=text_color_ax3)
after the plot command. This adds legend per axis and the color of the text is reset to black in the common legend.