Matplotlib: change the math font size and then go back to default

I learned from this Matplotlib question : change the math font size , how to change the default text text size in matplotlib. What am I doing:

from matplotlib import rcParams
rcParams['mathtext.default'] = 'regular'

which actually makes the LaTeX font equal to the size of a regular font.

I don’t know how to reset back to the default behavior, that is: LaTeX font looks a little smaller than a regular font.

I need this because I want the LaTeX font to look the same size as a regular font, on only one graph, and not on all the graphs of my figure that use LaTex formatting.

Here a MWEof how I create my figure:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec

# Generate random data.
x = np.random.randn(60)
y = np.random.randn(60)

fig = plt.figure(figsize=(5, 10))  # create the top-level container
gs = gridspec.GridSpec(6, 4)  # create a GridSpec object

ax0 = plt.subplot(gs[0:2, 0:4])
plt.scatter(x, y, s=20, label='aaa$_{subaaa}$')
handles, labels = ax0.get_legend_handles_labels()
ax0.legend(handles, labels, loc='upper right', numpoints=1, fontsize=14)
plt.ylabel('A$_y$', fontsize=16)
plt.xlabel('A$_x$', fontsize=16)

ax1 = plt.subplot(gs[2:4, 0:4])
# I want equal sized LaTeX fonts only on this plot.
from matplotlib import rcParams
rcParams['mathtext.default'] = 'regular'

plt.scatter(x, y, s=20, label='bbb$_{subbbb}$')
handles, labels = ax1.get_legend_handles_labels()
ax1.legend(handles, labels, loc='upper right', numpoints=1, fontsize=14)
plt.ylabel('B$_y$', fontsize=16)
plt.xlabel('B$_x$', fontsize=16)

# If I set either option below the line that sets the LaTeX font as 'regular'
# is overruled in the entire plot.
#rcParams['mathtext.default'] = 'it'
#plt.rcdefaults()

ax2 = plt.subplot(gs[4:6, 0:4])
plt.scatter(x, y, s=20, label='ccc$_{subccc}$')
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels, loc='upper right', numpoints=1, fontsize=14)
plt.ylabel('C$_y$', fontsize=16)
plt.xlabel('C$_x$', fontsize=16)

fig.tight_layout()

out_png = 'test_fig.png'
plt.savefig(out_png, dpi=150)
plt.close()
+4
2

, , mathtext.default , Axes , . , , Axes , :

# your plot code here

def wrap_rcparams(f, params):
    def _f(*args, **kw):
        backup = {key:plt.rcParams[key] for key in params}
        plt.rcParams.update(params)
        f(*args, **kw)
        plt.rcParams.update(backup)
    return _f

plt.rcParams['mathtext.default'] = 'it'
ax1.draw = wrap_rcparams(ax1.draw, {"mathtext.default":'regular'})

# save the figure here

:

enter image description here

+4

- rcParams, matplotlib tex ( , ). , ,

mpl.rcParams['text.usetex']=True

( ?) , , tex, () . \tiny, \small, \normalsize, \large, \large, \large, \huge \huge

MWE

plt.scatter(x, y, s=20, label=r'bbb{\Huge$_{subbbb}$}')

. .

+1

Source: https://habr.com/ru/post/1532905/


All Articles