Matplotlib 中的非 ASCII 字符 [英] Non-ASCII characters in Matplotlib
问题描述
我在 Matplotlib 中显示非 .
这个问题实际上可能有几个不同的原因:
默认字体不包括这些字形
您可以使用以下方法更改默认字体(在任何绘图完成之前!)
matplotlib.rc('font', family='Arial')
在某些版本的 matplotlib 中,您必须设置系列:
matplotlib.rc('font', **{'sans-serif' : 'Arial','家庭':'无衬线'})
(请注意,因为 sans-serif
在 **{}
语法中包含连字符,所以实际上是必需的.)
第一个命令将 sans-serif
字体系列更改为仅包含一种字体(在我的情况下是 Arial),第二个将默认字体系列设置为 sans-serif
.
其他选项包含在文档中.
您错误地创建/传递字符串对象到 Matplotlib
即使字体包含正确的字形,如果您忘记使用 u
来创建 Unicode 常量,Matplotlib 会有这种行为:
plt.xlabel("Średnia odległość między stacjami wsparcia a modelowaną [km]")
所以你需要添加u
:
plt.xlabel(u"Średnia odległość między stacjami wsparcia a modelowaną [km]")
另一个原因是您忘记在顶部放置UTF-8 魔术注释文件(我读到这可能是问题的根源):
# -*- 编码:utf-8 -*-
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):
How do I fix it?
A related question is Accented characters in 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.rc('font', **{'sans-serif' : 'Arial',
'family' : 'sans-serif'})
(Note that because sans-serif
contains a hyphen inside the **{}
syntax, it is actually necessary.)
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
.
Other options are included in the documentation.
You have improperly created/passed string objects into Matplotlib
Even if the font contains proper glyphs, if you forgot to use u
to create Unicode constants, Matplotlib will have this behaviour:
plt.xlabel("Średnia odległość między stacjami wsparcia a modelowaną [km]")
So you need to add 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):
# -*- coding: utf-8 -*-
这篇关于Matplotlib 中的非 ASCII 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!