Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib how to set legend's font type

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'})

But I want to use a Chinese font type and I have no idea what is the family name I should put in the line above. But I do have a fontproperties object to that Chinese font type. However, I haven't found a way to set the fontproperties of the legend.

So two questions:

  1. How to find the name of a particular font's family name
  2. How to set fontproperties of the legend
like image 884
Cheng Avatar asked Nov 04 '17 15:11

Cheng


1 Answers

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()

enter image description here

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.

like image 80
unutbu Avatar answered Oct 02 '22 06:10

unutbu