20

I would like to display a font in Times New Roman in the legend of a matplotlib plot. I have changed all other tick labels/axis labels/titles to Times New Roman, and have searched the documentation but I can only find how to change the font size in a legend using the prop argument in pyplot.legend()


Of course straight after posting, I found the answer. Solution for anyone else with the same issue:

import matplotlib as mpl  
mpl.rc('font',family='Times New Roman')
William Miller
  • 9,839
  • 3
  • 25
  • 46
Stu
  • 301
  • 1
  • 2
  • 4
  • 6
    add your answer as an answer so it can be accepted and taken out of the 'unanswered' questions queue. welcome to StackOverflow! – dax Feb 21 '14 at 11:49

3 Answers3

20

This wasn't showing up in google results so I'm going to post it as an answer. The rc parameters for font can be used to set a single default font.

Solution for anyone else with the same issue:

import matplotlib as mpl
mpl.rc('font',family='Times New Roman')
William Miller
  • 9,839
  • 3
  • 25
  • 46
Greg.S
  • 301
  • 1
  • 3
15

The .rc solution given changes the default font for all drawing.

Here is a solution for doing this when you don't want to change all the fonts, but just the font properties of the legend of this particular graph (a legend belonging to a particular axis object):

L = ax.legend()
plt.setp(L.texts, family='Consolas')

This allows you to choose a different font for the legend and the axes. I found this helpful when I needed a monospace font for my legend, but not for the axes -- allowing me to create a neat legend like this:

enter image description here

Note how the title is a different font than the legend - this gives me an alignment of numbers that would otherwise be hard to achieve.

Floris
  • 45,857
  • 6
  • 70
  • 122
  • good except that Consolas does not seem to come with standard installation or not a font family. `'monospace'` works for me – Dima Lituiev Aug 10 '17 at 15:35
  • @DimaLituiev - Consolas is a standard monospace font on a Mac. I guess you have a Windows machine? Anyway - this was intended as a guide, not a prescription... – Floris Aug 10 '17 at 16:12
  • On my mac 10.10, `open -a /Applications/Font\ Book.app` shows 9 monospace fonts, but only `Courier` `Courier New` and `monospace` work in Matplotlib 2.2.3. See also [font_manager](https://matplotlib.org/2.2.3/api/font_manager_api.html) – denis Jan 18 '19 at 11:15
10

I think this is the better way.

import matplotlib.font_manager as fm

## your font directory 
font_path = '/Users/frhyme/Library/Fonts/BMDOHYEON_otf.otf'

## font_name 
font_name = fm.FontProperties(fname=font_path).get_name()

plt.legend(prop={'family':font_name, 'size':20})
frhyme
  • 966
  • 1
  • 15
  • 24