【问题标题】:Use Unicode Greek letters in Matplotlib在 Matplotlib 中使用 Unicode 希腊字母
【发布时间】:2016-07-07 12:03:04
【问题描述】:

在 MATLAB 中,如果您在轴标签中键入“\alpha”,它将呈现“纯文本”希腊字符 alpha,而无需 Latex。我希望对 Matplotlib 的 Pyplot 做同样的事情。

按照How to use unicode symbols in matplotlib?,我尝试了以下方法:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

if __name__ == "__main__":
    plt.figure()
    prop = FontProperties()
    prop.set_file('STIXGeneral.ttf')
    plt.xlabel(u"\u2736", fontproperties=prop)
    plt.show()

x = np.linspace(-1,1,21)

plt.figure()
plt.plot(x,x)
plt.xlabel(u"\u03b1")        # Attempt at creating an axis label with a Unicode alpha
# plt.xlabel(r'$\alpha$')     # I'm aware that Latex is possible
plt.show()

但是,我收到一条以

结尾的错误消息
IOError: [Errno 2] No such file or directory: 'STIXGeneral.ttf'

如果我省略第 3-10 行,我不会收到错误消息,但绘图显示的是正方形而不是希腊字母 alpha:

可以用 Matplotlib 做到这一点吗? (我知道显示 Latex 的可能性,但更喜欢“纯文本”选项)。

【问题讨论】:

    标签: python matplotlib unicode


    【解决方案1】:

    一般来说,我认为这是因为您在 Windows 中运行它,对吗?

    Windows 中,您需要指定字体目录的确切位置,而不仅仅是文件名。

    这是我在installation of the font 之后所做的。我去了control panel-> font 找到字体的确切位置,在我的例子中是'C:\Windows\Fonts\STIXMath-Regular.otf'。然后我只是将代码更改为

    if __name__ == "__main__":
        plt.figure()
        prop = FontProperties(fname='C:\Windows\Fonts\STIXMath-Regular.otf')
    #    prop.set_file('STIXMath-Regular.otf')
        plt.xlabel(u"\u2736", fontproperties=prop)
    

    【讨论】:

    • 我实际上正在运行 Ubuntu 16.04,但发现指定 .ttf 文件的完整路径仍然可以正常工作。使用find 命令我发现它已经安装在/usr/share/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf
    • @khpeek,哈哈,我认为Linux 应该足够聪明,即使您没有指定任何目录名称也可以找到它!但是我只是进入了matplotlibset_file()的源代码,看起来不是LinuxWindows的错。在源代码中,它实际上并没有尝试搜索任何地方,这意味着您必须指定完整路径。
    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2021-07-16
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多