本文主要是介绍matplotlib legend写tex公式且控制字体,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
[1] 解决了 title 用 tex 和 x、y 轴 label 字体用 Times New Roman 的问题,但 legend 的 prop
参数中 不能设 usetex
(即 legend 似乎不能像 [1] 中 title 那样单独启用 usetex
)。参考 [3],matplotlib 其实不启用 usetex
也可以用 mathtext 写 tex 公式,但字体要调一下。
这里记录一种组合解决方案,使 legend 中的 mathtext 达到类似 [1] 中 title 的效果。用到两个设置的组合:
matplotlib.rcParams['mathtext.default'] = 'regular'
,使 mathtext 字体同非 mathtext 字体,本文即 Times New Roman;- 传给 legend 的
prop
参数的 dict 中,用'style': 'italic'
使字变斜;
Rendering
Code
- 对照 [1]
import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
matplotlib.rcParams['font.family'] = 'Times New Roman'
# 使字体同非 mathtext 字的字体,此处即 Times New Roman
matplotlib.rcParams['mathtext.default'] = 'regular'
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocatorY = [0.6819, 0.7017, 0.7049, 0.7228, 0.7198, 0.7272, 0.7256, 0.731]
X = list(range(len(Y)))font_title = {'family': 'Times New Roman','weight': 'normal','size': 30,# 'style': 'italic''usetex' : True, # title 可以单独启用 usetex
}font_legend = {'family': 'Times New Roman','weight': 'normal','size': 20,'style': 'italic' # 使字变斜# 'usetex' : True, # legend 无得设 `usetex` 这项
}fig = plt.figure()
plt.plot(X, Y, marker="o", clip_on=False,label=r"$T\rightarrow I$") # legend 亦画箭头plt.xlim((X[0], X[-1]))
plt.ylim((min(Y), max(Y)))
plt.title("$I\\rightarrow T$", font_title) # title 设置
plt.xlabel("# Tom", fontsize=30)
plt.ylabel("Jerry", fontsize=30)
plt.grid()plt.legend(loc="best", prop=font_legend) # legend 设置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('legend.png', bbox_inches='tight', pad_inches=0.05)
plt.close(fig)
References
- matplotlib的text.usetex会影响字体
- Writing mathematical expressions
- How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?
这篇关于matplotlib legend写tex公式且控制字体的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!