如何用Python matplotlib将LaTeX公式转换为SVG?

摘要:使用 python matplotlib 将 LaTex 公式转为 svg,从而方便插入无法打出所需公式的ppt中。 import matplotlib.pyplot as plt plt.rcParams['tex
使用 python matplotlib 将 LaTex 公式转为 svg,从而方便插入无法打出所需公式的ppt中。 import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True plt.rcParams['text.latex.preamble'] = r'\usepackage{bm}' # 或 \usepackage{amsmath} plt.rcParams['svg.fonttype'] = 'none' def latex_formula2svg(text, font_size=12, save_fig='formula.svg'): plt.rcParams['font.size'] = font_size fig, ax = plt.subplots() txt = ax.text(0.5, 0.5, text, ha='center', va='center', transform=ax.transAxes) ax.axis('off') fig.canvas.draw() bbox = txt.get_window_extent(renderer=fig.canvas.get_renderer()) fig.set_size_inches(bbox.width/fig.dpi, bbox.height/fig.dpi) fig.savefig(save_fig, bbox_inches='tight', pad_inches=0, transparent=True) plt.show() text = r'$\tilde{a}\boldsymbol{test}$' latex_formula2svg(text, font_size=9, save_fig = 'formula.svg')