[英]Non-ASCII characters in Matplotlib
I have a problem displaying non- ASCII characters in Matplotlib, these characters are rendered as small boxes instead of a proper font, it looks like (I filled these boxes with red paint to hightlight them):我在 Matplotlib 中显示非ASCII字符时遇到问题,这些字符呈现为小框而不是正确的字体,看起来像(我用红色颜料填充这些框以突出显示它们):
How do I fix it?我如何解决它?
A related question is Accented characters in Matplotlib .一个相关的问题是Matplotlib 中的重音字符。
This problem may actually have a couple of different causes: 这个问题实际上可能有几个不同的原因:
The default font does not include these glyphs 默认字体不包括这些字形
You may change the default font using the following (before any plotting is done!) 您可以使用以下内容更改默认字体(在任何绘图完成之前!)
matplotlib.rc('font', family='Arial')
In some versions of matplotlib you'll have to set the family: 在matplotlib的某些版本中,您必须设置系列:
matplotlib.rc('font', **{'sans-serif' : 'Arial',
'family' : 'sans-serif'})
(Note that because sans-serif
contains a hyphen inside the **{}
syntax, it is actually necessary.) (注意,因为
sans-serif
在**{}
语法中包含连字符,所以实际上是必要的。)
The first command changes the sans-serif
font family to contain only one font (in my case it was Arial ), the second sets the default font family to sans-serif
. 第一个命令将
sans-serif
字体系列更改为仅包含一个字体(在我的例子中是Arial ),第二个命令将默认字体系列设置为sans-serif
。
Other options are included in the documentation . 其他选项包含在文档中 。
You have improperly created/passed string objects into Matplotlib 您已将不正确的字符串对象创建/传递到Matplotlib中
Even if the font contains proper glyphs, if you forgot to use u
to create Unicode constants, Matplotlib will have this behaviour: 即使字体包含正确的字形,如果您忘记使用
u
来创建Unicode常量,Matplotlib也会出现这种情况:
plt.xlabel("Średnia odległość między stacjami wsparcia a modelowaną [km]")
So you need to add u
: 所以你需要添加
u
:
plt.xlabel(u"Średnia odległość między stacjami wsparcia a modelowaną [km]")
Another cause is that you forgot to put a UTF-8 magic comment on top of the file (I read that this might be the source of the problem ): 另一个原因是你忘了在文件顶部放置一个UTF-8魔术评论(我读到这可能是问题的根源 ):
# -*- coding: utf-8 -*-
jb.
's answer is good enough. 的答案已经足够好了。 In case you want to avoid adding
u
, use this 如果您想避免添加
u
,请使用此选项
from __future__ import unicode_literals
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.