I want to change the font type of the legend texts in Matplotlib. I know I can do something like this:
plt.legend(prop={\'family\': \'Arial\'})
Pass the FontProperties object (such as font
below) to ax.legend
via the prop
parameter:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
ax.plot(np.sin(x)/x, label='Mexican hat')
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
ax.legend(prop=font)
plt.show()
On Ubuntu, you can make new fonts available to your system by running
fc-cache -f -v /path/to/fonts/directory
I'm not sure how it is done on other OSes, or how universal fc-cache
is on other flavors of Unix.
Once you've installed your font(s) so that your OS knows about them, you can cause matplotlib to regenerate its fontList by deleting the files in ~/.cache/fontconfig
and ~/.cache/matplotlib
.
The ~/.cache/matplotlib/fontList.json
file gives you a humanly-readable list of all the fonts matplotlib knows about. There, you'll find entries that look like this:
{
"weight": "bold",
"stretch": "normal",
"fname": "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf",
"_class": "FontEntry",
"name": "Comic Sans MS",
"style": "normal",
"size": "scalable",
"variant": "normal"
},
Notice that the fname
is the path to the underlying ttf file, and that there is a name
property as well. You can specify the FontProperties object by the path to the ttf file:
font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf")
or by name:
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
If you do not wish to install your font system-wide, you can specify the FontProperties
object by fname
path, thus by-passing the need to call fc-cache
and messing with ~/.cache
.