我如何在matplotlib中使用普通话字符? [英] How do you i use mandarin characters in matplotlib?
问题描述
我一直在尝试使用matplotlib的文本或用普通话汉字注释模块.它最终以某种方式显示框.有什么想法吗?
I have been trying to use matplotlib's text or annotate modules with mandarin Chinese characters. Somehow it ends up showing boxes. Any idea on this ?
推荐答案
以下是对我适用于Python 2.7和Python 3.3的解决方案,同时将text
和annotate
方法与中文一起使用.
Here is a solution that works for me on Python 2.7 and Python 3.3, using both text
and annotate
methods with Chinese.
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
ax = fig.add_subplot(111)
ChineseFont1 = FontProperties(fname = 'C:\\Windows\\Fonts\\simsun.ttc')
ChineseFont2 = FontProperties('SimHei')
ax.text(3, 2, u'我中文是写得到的', fontproperties = ChineseFont1)
ax.text(5, 1, u'我中文是写得到的', fontproperties = ChineseFont2)
ax.annotate(u'我中文是写得到的', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05),
fontproperties = ChineseFont1)
ax.axis([0, 10, 0, 10])
plt.show()
ChineseFont1
被硬编码为字体文件,而ChineseFont2
通过家族名称获取字体(但是对于ChineseFont2
,我不得不尝试一对才能找到可行的字体).两者都是我的系统所特有的,因为它们引用了我拥有的字体,因此您很可能需要将它们更改为系统上的引用字体/路径.
ChineseFont1
is hard coded to a font file, while ChineseFont2
grabs a font by family name (but for ChineseFont2
I had to try a couple to find one that would work). Both of those are particular to my system, in that they reference fonts I have, so you quite likely will need to change them to reference fonts/paths on your system.
默认加载的字体似乎不支持汉字,因此主要是字体选择问题.
The font loaded by default doesn't seem to support Chinese characters, so it was primarily a font choice issue.
这篇关于我如何在matplotlib中使用普通话字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!