【问题标题】:Matplotlib: Change math font size and then go back to defaultMatplotlib:更改数学字体大小,然后返回默认值
【发布时间】:2014-04-29 10:17:50
【问题描述】:

我从这个问题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()

【问题讨论】:

  • 您是否要将所有rcParams 重置为默认值?如果是这样,请使用plt.rcdefaults()
  • 或者只是把默认值放回去it
  • 另外,如果你只想要特定的 mathtex 表达式的常规非斜体字体,只需 r'$\mathregular{your_expression_here}$'
  • 我尝试过plt.rcdefaults() 并设置rcParams['mathtext.default'] = 'it',但这两种方法都给了我同样的问题:它们要么影响整个数字,要么根本没有影响。让我提供一个更详细的示例来说明我的图是如何设置的,以便让你们更清楚地了解我的意思。
  • 好的,我添加了MWE。请注意,我只想覆盖中间图的默认行为,而不是其余部分。

标签: python fonts matplotlib latex


【解决方案1】:

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

这是输出:

【讨论】:

  • 这个解决方案比我想象的要复杂得多:) 谢谢@HYRY,我会等一会儿,如果没有更简单的解决方案,我会将此标记为已接受.
  • 不错的答案。将其包装在上下文管理器中可以更好地使用with(请参阅下面的答案)。
【解决方案2】:

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

只有在这种情况下才能在图例中获得更大的下标字体。所有其他情况都立即正确处理

【讨论】:

    【解决方案3】:

    这是一个很好的pythonic方法来临时更改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
    

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

    with temp_rcParams({'text.usetex': True, 'mathtext.default': 'regular'}):
        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()
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多