Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 901
Stu Avatar asked Feb 21 '14 11:02

Stu


People also ask

How do I change the legend box size in Matplotlib?

To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.

How do I change the font size in legend?

Direct link to this answer You can change the font size for a MATLAB legend by setting the 'FontSize' property of the Legend object. For example, plot four lines. Create a legend and assign the Legend object to the variable 'lgd'. Then, use dot notation to access the 'FontSize' property and set the value to 14 points.

How do I change the legend color in Matplotlib?

To place the legend, use legend() method with location of the legend and store the returned value to set the color of the text. To set the color of the text, use set_color() method with green color. To display the figure, use show() method.


2 Answers

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')
like image 194
Greg.S Avatar answered Oct 17 '22 02:10

Greg.S


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.

like image 14
Floris Avatar answered Oct 17 '22 03:10

Floris