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')
To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.
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.
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.
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')
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With