【问题标题】:How to use unicode symbols in matplotlib?如何在 matplotlib 中使用 unicode 符号?
【发布时间】:2015-05-08 11:31:32
【问题描述】:
import matplotlib.pyplot as pyplot

pyplot.figure()
pyplot.xlabel(u"\u2736")
pyplot.show()

这是我可以创建的最简单的代码来显示我的问题。轴标签符号是一个六角星,但它显示为一个框。如何更改它以显示星星?我试过添加评论:

#-*- coding: utf-8 -*-

就像之前建议的答案一样,但它不起作用,以及使用 matplotlib.rcmatplotlib.rcParams 也不起作用。帮助将不胜感激。

【问题讨论】:

  • \u2736代表明星吗?

标签: python unicode matplotlib


【解决方案1】:

您需要具有给定 unicode 字符的字体,STIX 字体应包含星号。您需要找到或下载 STIX 字体,当然任何其他带有给定符号的 ttf 文件都可以。

import matplotlib.pyplot as pyplot
from matplotlib.font_manager import FontProperties

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

【讨论】:

    【解决方案2】:

    补充@arjenve 的回答。要绘制一个 Unicode 字符,首先,找到包含该字符的字体,其次,使用该字体在 Matplotlib 中绘制字符

    查找包含该字符的字体

    根据this post,我们可以使用fontTools包来查找哪个字体包含我们要绘制的字符。

    from fontTools.ttLib import TTFont
    import matplotlib.font_manager as mfm
    
    def char_in_font(unicode_char, font):
        for cmap in font['cmap'].tables:
            if cmap.isUnicode():
                if ord(unicode_char) in cmap.cmap:
                    return True
        return False
    
    uni_char =  u"✹"
    # or uni_char = u"\u2739"
    
    font_info = [(f.fname, f.name) for f in mfm.fontManager.ttflist]
    
    for i, font in enumerate(font_info):
        if char_in_font(uni_char, TTFont(font[0])):
            print(font[0], font[1])
    

    此脚本将打印字体路径和字体名称列表(所有这些字体都支持该 Unicode 字符)。示例输出如下所示

    然后,我们可以使用下面的脚本来绘制这个角色(见下图)

    import matplotlib.pyplot as plt
    import matplotlib.font_manager as mfm
    
    font_path = '/usr/share/fonts/gnu-free/FreeSerif.ttf'
    prop = mfm.FontProperties(fname=font_path)
    plt.text(0.5, 0.5, s=uni_char, fontproperties=prop, fontsize=20)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 2014-06-17
      • 2015-04-22
      • 1970-01-01
      • 2014-01-23
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多