【问题标题】:Why doesn't matplotlib use the specified font here?为什么 matplotlib 这里不使用指定的字体?
【发布时间】:2019-04-17 19:49:55
【问题描述】:

(在 Win10 上使用 Python 3.6.1,在一个基本上只安装了 numpy/pandas/matplotlib 的 virtualenv 中,用于处理数字的东西。我没有安装 Tkinter,我更愿意保持这种方式。)

我有以下测试代码,试图静态呈现 MathML 文本:

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plot


def render(mathml):
    plot.clf()
    plot.rc('font', family='monospace', size=72)
    plot.axis('off')
    plot.text(0, 0, f'{mathml}')
    plot.savefig(f'hax.png')


render('$lorem^{ipsum}$')

生成的test.png 以默认字体(DejaVu Sans Oblique)显示文本,而不是等宽字体:

明确指定字体(例如family='Courier New')也无效,更改输出格式也无效。文本已正确调整大小,并且没有出现错误或警告 - 输出只是没有显示正确的字体。

这里发生了什么?我该如何解决?

【问题讨论】:

  • 我没有安装 Tkinter,我希望保持这种状态tkinter 已经是 Python 标准库的一部分,所以它已经安装了。跨度>
  • Windows 标准安装程序完全可以省略它(连同 IDLE)。

标签: python python-3.x matplotlib


【解决方案1】:

数学字体选项根据the tutorial

DejaVu Sans(默认)、DejaVu Serif、Computer Modern 字体(来自 (La)TeX)、STIX 字体(与 Times 完美融合)或您提供的 Unicode 字体

坚持默认,使用\mathtt可以得到类似“打字机”的感觉

import matplotlib.pyplot as plt


def render(mathml):
    plt.clf()
    plt.rc('font', size=72)
    plt.axis('off')
    plt.text(0, 0, f'$\\mathtt{{{mathml}}}$')
    plt.show()

render('lorem^{ipsum}')

可以通过mathtext.fontset rc 参数在自定义字体集中使用数学文本。

plt.rcParams["mathtext.fontset"] = "custom"

对于 courier 的新字体,可能是这样的

import matplotlib.pyplot as plt

def render(mathml):
    plt.clf()
    plt.rc('font', size=72)
    plt.rc('mathtext', fontset="custom", tt="Courier New")
    plt.axis('off')
    plt.text(0, 0, f'$\\mathtt{{{mathml}}}$')
    plt.show()

render('lorem^{ipsum}')

【讨论】:

  • 我什至没有想到可能需要单独的方法来为 MathML 文本和普通文本选择字体。我用一个普通的'lorem ipsum' 字符串测试了原始代码,它确实有效。尝试这种方法,起初我得到一个错误,\mathtt{ 是一个未知符号。这是一种误导——我忘记从测试输入中去除$,所以渲染引擎可能只是看到$\mathtt{$,后面跟着垃圾。现在工作得很漂亮。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2012-09-29
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多