想用 matplotlib.rcParams['text.usetex'] = True
启用对 latex 的支持,在 title 画个右箭头(
→
\rightarrow
→),但在全局启用会影响 x、y 轴 label 的字体。
想要同时保住 title 用 tex 画的箭头,和其它地方的 Times New Roman 字体,需要对 plt.title
单独用个 dict 启用 usetex,而不在全局开。
global
- 设置
matplotlib.rcParams['text.usetex'] = True
import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
matplotlib.rcParams['text.usetex'] = True # 全局开启
matplotlib.rcParams['font.family'] = 'Times New Roman' # 指定字体
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
Y = [0.6819, 0.7017, 0.7049, 0.7228, 0.7198, 0.7272, 0.7256, 0.731]
X = list(range(len(Y)))
fig = plt.figure()
plt.plot(X, Y, marker="o", clip_on=False)
plt.xlim((X[0], X[-1]))
plt.ylim((min(Y), max(Y)))
plt.title("$I\\rightarrow T$", fontsize=30) # 只用指定 fontsize
plt.xlabel("\\# Tom", fontsize=30) # 要用 `\` 对 `#` 转义
plt.ylabel("Jerry", fontsize=30)
plt.grid()
ax = plt.gca()
grid_margin = MultipleLocator(0.05)
# ax.xaxis.set_major_locator(grid_margin)
ax.yaxis.set_major_locator(grid_margin)
ax.set_aspect(0.5 / ax.get_data_ratio(), adjustable='box')
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(20)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(20)
plt.tight_layout()
fig.savefig('global.png', bbox_inches='tight', pad_inches=0.05)
plt.close(fig)
- 效果如下。此时 x、y 轴的 label 其实并不是 Times New Roman,被影响了。
local
- 用
font_title
单独指定 title 样式
import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
# matplotlib.rcParams['text.usetex'] = True # 不在全局开
matplotlib.rcParams['font.family'] = 'Times New Roman' # 同样指定字体
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
Y = [0.6819, 0.7017, 0.7049, 0.7228, 0.7198, 0.7272, 0.7256, 0.731]
X = list(range(len(Y)))
font_title = { # 用 dict 单独指定 title 样式
'family': 'Times New Roman',
'weight': 'normal',
'size': 30,
'usetex' : True,
}
fig = plt.figure()
plt.plot(X, Y, marker="o", clip_on=False)
plt.xlim((X[0], X[-1]))
plt.ylim((min(Y), max(Y)))
# plt.title("$I\\rightarrow T$", fontsize=30)
plt.title("$I\\rightarrow T$", font_title) # 用 dict 指定
plt.xlabel("# Tom", fontsize=30) # **不**用 `\` 转义
plt.ylabel("Jerry", fontsize=30)
plt.grid()
ax = plt.gca()
grid_margin = MultipleLocator(0.05)
# ax.xaxis.set_major_locator(grid_margin)
ax.yaxis.set_major_locator(grid_margin)
ax.set_aspect(0.5 / ax.get_data_ratio(), adjustable='box')
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(20)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(20)
plt.tight_layout()
fig.savefig('local.png', bbox_inches='tight', pad_inches=0.05)
plt.close(fig)
- 效果如下。此时 x、y 轴的 label 好像才是 Times New Roman。