Home > OS >  Matplotlib control text properties for legend title
Matplotlib control text properties for legend title

Time:05-14

I have a matplotlib plot with a title in the legend and the properties of the title text I want to control, like the font family size etc.


import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.font_manager as font_manager

font = font_manager.FontProperties(family='Comic Sans MS',
                                   weight='bold',
                                   style='normal', 
                                   size=32)


fig,ax = plt.subplots()
x = np.linspace(0,2*np.pi)


# plot lines
linu1,= ax.plot(x,np.sin(x),label='u$_1$', linewidth=2)
ax.legend(title="My Title", prop=font)


# set axes labels, labelpad is offset of the label from the axis
ax.set_xlabel(r'$y (\AA)$ ', fontsize=21,fontdict={'fontsize': 8, 'fontweight': 'medium','fontname':"Serif"})
ax.set_ylabel('x', fontsize=21)


plt.show()

The prop argument in the legend option only controls the text for the lines but not the title (i.e. "My title"). How do I change the properties of the title text?

CodePudding user response:

The title has a dedicated property for the title, which specifies the settings.

ax.legend(title="My Title", title_fontproperties=font, prop=font)

enter image description here

  • Related