如何在plotlib中使用unicode matlib符号?

2024-10-01 17:38:00 发布

您现在位置:Python中文网/ 问答频道 /正文

import matplotlib.pyplot as pyplot

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

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

^{pr2}$

就像前面的答案所建议的那样,但是它不起作用,以及使用matplotlib.rc或{}也不起作用。如有帮助,不胜感激。在


Tags: 答案代码importmatplotlibasshow评论符号
2条回答

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

补充@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

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

^{pr2}$

enter image description here

相关问题 更多 >

    热门问题