Matplotlib 如何输出各种字体

matplotlib 默认输出的是无衬线字体,因此,修改无衬线字体的配置即可正确输出中文:

import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["STSong"]

一般来说, matplotlib 会将字体的配置保存在 ~/.matplotlib/fontlist.json 里,比如随便找一个 entry 是这样结构的:

{
      "fname": "fonts/afm/phvro8an.afm",
      "name": "Helvetica", 
      "style": "italic",
      "variant": "normal",
      "weight": "medium",
      "stretch": "condensed",
      "size": "scalable",
      "__class__": "FontEntry"
}

name 就表示字体的名称,fname 是该字体的目录,可以在该 json 文件里添加新字体。

在 matplotlib 中,plt.titleplt.xlabelplt.ylabelplt.textplt.legend 这几个函数是涉及添加文字内容的。

修改字体类型或大小的方式,plt.titleplt.xlabelplt.ylabelplt.text 相同,使用 fontdict 参数;plt.legend 可以使用

fontdict 是一个字典,见:https://www.tutorialexample.com/understand-matplotlib-fontdict-a-beginner-guide-matplotlib-tutorial/

Key Value
family such as serif, fantasy, Tahoma, monospace,’Times New Roman’ et al. You should notice: you can set font-family or font in this key.
color darkred, red, black
weight ‘light’, ‘normal’, ‘medium’, ‘semibold’, ‘bold’, ‘heavy’, ‘black’
size 10, 12, ....
style ‘normal’, ‘italic’, ‘oblique’

此外,还可以用其它关键词参数,如 fontsizefontfamilyfontstyle 来修改字体相关参数。

例:

plt.plot([1, 2, 3, 4])
plt.title("中文字体")
plt.xlabel("English Italic", 
           fontdict={"family": "Times New Roman", "style": "italic"})
plt.ylabel("English Regular", 
           fontdict={"family": "Times New Roman", "style": "normal"})
plt.text(x=0.1, y=1.9, s="Random Text", 
         fontsize=16, fontstyle="italic", fontfamily="Times New Roman")
plt.text(x=1.9, y=2.5, s="\it{Tex Text} $a^2 + b^2$", usetex=True, fontsize=14)
plt.legend(["$\Gamma, \mathit{\Gamma}$ 中文"])

结果如图:


plt.legend 只提供了 prop 参数接受一个 matplotlib.font_manager.FontProperties 来指定字体,或者是一个类似的字典。

import matplotlib.font_manager.FontProperties as FontProperties

FontProperties(family=None, 
               style=None, 
               variant=None, 
               weight=None, 
               stretch=None, 
               size=None, 
               fname=None, 
               math_fontfamily=None)

plt.legend(["$\Gamma, \mathit{\Gamma}$ 123abc"], 
           prop={"family": "Times New Roman", "size": 16})

但这样的问题是,$$ 符号输出的时候,用的是 matplotlib 自带的对 LaTex 的支持,它支持不是特别完整,不能输出一些很专门的符号,比如 \mathit{\Gamma}\mathbb{E},这时候可以用 plt.rc('text', usetex=True) 设置全局 LaTex 输出,程序会调用 LaTex 来渲染这句话,甚至可以调用宏包来输出更复杂的数学公式!

默认使用 PDFLaTex,可以调整参数改成 XeLaTex 来获得对中文的支持!甚至可以添加导言区。

import matplotlib as mpl
mpl.use("pgf")
plt.rcParams.update({
    "pgf.texsystem": "xelatex",
    "pgf.preamble": "\n".join([
         r"\usepackage{amsfonts}",
         r"\usepackage{xeCJK}",
         r"\usepackage[utf8x]{inputenc}",
         r"\usepackage[T1]{fontenc}",
         r"\usepackage{fontspec}",
         r"\setmainfont{Times New Roman}",
         r"\usepackage{amsmath}",
         # r"\setCJKmainfont{STSong}",
    ]),
})

如果不是要在一句话里同时输出中文和复杂的公式,那么用 PDFLaTex 也足够了。

比如加入 url 宏包,可以生成带超链接的 pdf 图片:

plt.figure()
plt.plot([1, 2, 3, 4])
plt.title("中文标题", usetex=False, fontfamily="STSong")
plt.xlabel(r"$\mathbb{E}[X] = \frac{1}{n^2+1}$, \url{http://baidu.com}", usetex=True)
plt.ylabel("\\textrm{English Regular}, $mc^2, \mathrm{VaR}$")
plt.text(1.5,2.5, "\\textit{Tex Text}  \\texttt{monospace} $a^2 + b^2 \mathit{A} \Rightarrow + \mathscr{A}$", usetex=True)
# plt.legend(["$\Gamma, \mathit{\Gamma}$"])
plt.savefig('ex3.pdf', bbox_inches="tight")
# plt.show()

效果如下:


推荐阅读:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容