Matplotlib中的非ASCII字符 [英] Non-ASCII characters in Matplotlib

查看:98
本文介绍了Matplotlib中的非ASCII字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matplotlib中显示非 ASCII 字符时遇到问题,这些字符呈现为小字体框而不是适当的字体,看起来像(我用红色油漆填充了这些框以突出显示它们):

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中的重音字符 .

A related question is Accented characters in Matplotlib.

推荐答案

此问题实际上可能有两个不同的原因:

This problem may actually have a couple of different causes:

默认字体不包含这些字形

您可以使用以下命令更改默认字体(在完成任何绘制之前!)

You may change the default font using the following (before any plotting is done!)

matplotlib.rc('font', family='Arial')

在某些版本的matplotlib中,您必须设置族:

In some versions of matplotlib you'll have to set the family:

matplotlib.rc('font', **{'sans-serif' : 'Arial',
                         'family' : 'sans-serif'})

(请注意,由于sans-serif**{}语法中包含连字符,因此实际上是必需的.)

(Note that because sans-serif contains a hyphen inside the **{} syntax, it is actually necessary.)

第一个命令将sans-serif字体系列更改为仅包含一种字体(在我的情况下为 Arial ),第二个将默认字体系列设置为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.

文档中包含了其他选项 .

Other options are included in the documentation.

您没有正确地将字符串对象创建/传递给Matplotlib

即使字体包含正确的字形,如果您忘记使用u来创建 Unicode 常量,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]")

因此您需要添加u:

plt.xlabel(u"Średnia odległość między stacjami wsparcia a modelowaną [km]")

另一个原因是您忘记在顶部放置 UTF-8 魔术注释文件的内容(我听说这可能是问题的根源):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆