如何在matplotlib中使用unicode符号?

时间:2015-03-06 19:10:40

标签: python unicode matplotlib

import matplotlib.pyplot as pyplot

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

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

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

与先前的建议相似,但它没有用,以及使用matplotlib.rcmatplotlib.rcParams也没有效果。帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您需要一个具有给定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()

答案 1 :(得分:0)

补充@ 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字符)。样本输出如下所示

enter image description here

然后,我们可以使用以下脚本绘制此角色(见下图)

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()

enter image description here

相关问题