Stu
Stu

Reputation: 331

How to change legend fontname in matplotlib

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

Upvotes: 23

Views: 45818

Answers (4)

user_n_8093
user_n_8093

Reputation: 31

Here is an example from 2023

plt.legend(
    labels,
    bbox_to_anchor=[1, 0, 0.5, 1],
    prop={'family':'monospace'}
)

prop={'family':'monospace'} - change legend font
bbox_to_anchor=[1, 0, 0.5, 1] - move legend to right upper conner

Upvotes: 2

Greg.S
Greg.S

Reputation: 341

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

Upvotes: 24

frhyme
frhyme

Reputation: 1036

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

Upvotes: 13

Floris
Floris

Reputation: 46445

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.

Upvotes: 18

Related Questions