matplotlib legend写tex公式且控制字体

编程入门 行业动态 更新时间:2024-10-08 00:26:59

matplotlib legend写tex<a href=https://www.elefans.com/category/jswz/34/1769303.html style=公式且控制字体"/>

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

  1. matplotlib的text.usetex会影响字体
  2. Writing mathematical expressions
  3. How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

更多推荐

matplotlib legend写tex公式且控制字体

本文发布于:2024-02-13 16:14:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:公式   字体   matplotlib   legend   tex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!