[英]Matplotlib: Change math font size and then go back to default
我从这个问题中学到了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()
我认为这是因为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
这是输出:
另一个解决方案是更改 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
方法来临时更改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}):
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()
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.