villaa
villaa

Reputation: 1239

Comprehensively setting matplotlib font parameters

From what I understand of this documentation matplotlib provides 3 ways to change the style parameters for plotting (things like axes.grid). Those ways are: using style sheets to set many parameters at a time; setting specific parameters through matplotlib.rcParams or matplotlib.rc; or using a matplotlibrc file to set defaults.

I would like to understand if all of the parameters are accessible in each of the methods I listed above and where I can find a comprehensive list of all of the parameters.

I have tried to understand this from the linked documentation, but I often fail. A specific example is setting the axis font. I typically use a combination like this:

axis_font = {'fontname':'Arial', 'size':'32'}
ax.set_ylabel('some axis title',**axis_font)

But it is not clear what matplotlib parameter (if any) I have set. Does there exist a parameter for the axis font that could be included in a style file for example?

Other attempts in my code include confusing blocks like:

legend_font = {'fontname':'Arial', 'size':'22'}
#fonts global settings
matplotlib.rc('font',family=legend_font['fontname'])

By the names it seems like it would be changing the legend font, but actually it is clearly setting the parameter for the overall font. And the size is not being used. Are there matplotlib parameters for specifically the legend font and legend size?

The things I've tried are:

Upvotes: 2

Views: 1889

Answers (1)

William Miller
William Miller

Reputation: 10320

The rcParams property which changes the font is font.family it accepts 'serif', 'sans-serif', 'cursive', 'fantasy', and 'monospace' as outlined in the linked sample matplotlibrc file. If text.usetex is False it also accepts any concrete font name or list of font names - which will be tried in the order they are specified until one works.

This method applies the specified font name to the entire figure (and to all figures when done globally). If you want to modify the font family for an individual Text instance (i.e. an axis label) you can use matplotlib.text.Text.set_family() (which is an alias for matplotlib.text.Text.set_fontfamily())

import matplotlib.pyplot as plt

ylabel = plt.ylabel("Y Label")
ylabel.set_family("DejaVu Serif")
plt.xlabel("X Label")

plt.show()

enter image description here

And to set the font family for just a legend instance you can use plt.setp, e.g.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

ylabel = plt.ylabel("Y Label")
plt.xlabel("X Label")
ylabel.set_family("DejaVu Serif")

legend = plt.legend(handles = [mpatches.Patch(color='grey', label="Label")])
plt.setp(legend.texts, family="EB Garamond")

plt.show()

enter image description here


Note that this method will not work when text.usetex is True.

Upvotes: 1

Related Questions