Matplotlib:更改数学字体大小,然后返回默认值

问题描述 投票:7回答:3

我从问题Matplotlib: Change math font size中了解到如何更改matplotlib中数学文本的默认大小。我要做的是:

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

有效地使LaTeX字体的大小与常规字体相同。

我不知道如何将其重置为默认行为,即:LaTeX字体看起来比常规字体小。

我需要这个,因为我希望LaTeX字体仅在一个绘图上看起来与常规字体相同,而不是在我图中使用LaTex数学格式的所有绘图上看起来都与常规字体相同。

这里是我如何创建人物的MWE

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()
python fonts matplotlib latex
3个回答
4
投票

我认为这是因为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

这里是输出:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9XSXBVRC5wbmcifQ==” alt =“在此处输入图像描述”>


1
投票

[另一种解决方案是更改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}$}')

仅在那种情况下才能在图例中获得更大的下标字体。立即处理所有其他情况

这是临时更改rcParams并自动将其重新更改为一个好方法。首先,我们定义一个可以与with一起使用的上下文管理器:

from contextlib import contextmanager

@contextmanager
def temp_rcParams(params):
    backup = {key:plt.rcParams[key] for key in params}  # Backup old rcParams
    plt.rcParams.update(params) # Change rcParams as desired by user
    try:
        yield None
    finally:
        plt.rcParams.update(backup) # Restore previous rcParams

然后,我们可以使用它来临时更改一个特定图的rcParam:

with temp_rcParams({'text.usetex': True}):
    plt.figure()
    plt.plot([1,2,3,4], [1,4,9,16])
    plt.show()

# Another plot with unchanged options here
plt.figure()
plt.plot([1,2,3,4], [1,4,9,16])
plt.show()

结果:

enter image description here


0
投票

这是临时更改rcParams并自动将其重新更改为一个好方法。首先,我们定义一个可以与with一起使用的上下文管理器:

© www.soinside.com 2019 - 2024. All rights reserved.