How to change the font text color in a legend?

Is there a way to change the font color of the legend on matplotlib chart?

Especially in cases where the plot background is dark, the black text by default in the legend is difficult or impossible to read.

+7
python matplotlib fonts colors legend
source share
3 answers

call Legend.get_texts() will get a list of the Text object in the legend object:

 import pylab as pl pl.plot(randn(100), label="randn") l = legend() for text in l.get_texts(): text.set_color("red") 
+10
source share

You can also do this with setp ():

 import pylab as plt leg = plt.legend(framealpha = 0, loc = 'best') for text in leg.get_texts(): plt.setp(text, color = 'w') 

this method also allows you to set the font and any number of other font properties on one line (here: http://matplotlib.org/users/text_props.html )

full example:

 import pylab as plt x = range(100) y1 = range(100,200) y2 = range(50,150) fig = plt.figure(facecolor = 'k') ax = fig.add_subplot(111, axisbg = 'k') ax.tick_params(color='w', labelcolor='w') for spine in ax.spines.values(): spine.set_edgecolor('w') ax.plot(x, y1, c = 'w', label = 'y1') ax.plot(x, y2, c = 'g', label = 'y2') leg = plt.legend(framealpha = 0, loc = 'best') for text in leg.get_texts(): plt.setp(text, color = 'w') plt.show() 
+3
source share

Since plt.setp translates through iterators, you can also change the text color in one line:

 # Show some cool graphs legend = plt.legend() plt.setp(legend.get_texts(), color='w') 

The last line will apply color to all elements in the text collection.

+2
source share

All Articles