python - 当 DISPLAY 在 python 中未定义时,使用 matplotlib 生成带有 UTF-8 标签的 JPG

标签 python utf-8 matplotlib

我知道如何在 DISPLAY 未定义时保存绘图:

Generating a PNG with matplotlib when DISPLAY is undefined

但是当我在图中使用 UTF-8 字符执行此操作时,这些字符将被文件中的方 block 替换。这是我的代码示例:

# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt

plt.plot(range(10))

plt.xlabel(u'وَبَوِّئْنا')

plt.savefig('test.jpg',format='jpg')

如果“Agg”行被注释掉,则定义 DISPLAY 时输出文件看起来很好。我在 Mac 和 CentOS 上都发生过这种情况。有人可以告诉我如何创建一个在 DISPLAY 未定义时正确显示 UTF 字符的 jpg 吗?

提前谢谢您!

最佳答案

我认为你只需要指定一个可用的字体:

# -*- coding: utf-8 -*-

import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt

plt.plot(range(10))
# you might need to change this to be a font that you know works for your gylphs
# that you have installed
plt.xlabel(u'وَبَوِّئْنا', name='Arial')

plt.savefig('test.jpg',format='jpg')

enter image description here

您可以修改 rcparam 的 font.seriffont.sans-serif 字段来更改默认字体搜索顺序,将具有字形的字体放在前面。

关于python - 当 DISPLAY 在 python 中未定义时,使用 matplotlib 生成带有 UTF-8 标签的 JPG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579692/

相关文章:

python - Seaborn 热图 : y axis ticks and annot

python - 如何向堆积的 Pandas 区域图添加黑线?

python - Fit 和 inverse_transform 中不同形状的 MinMaxScaler

python - Python 有流式正则表达式模块吗?

java - 不在 spring MVC 中渲染汉字

utf-8 - 在 HTTP header 中指定字符集

matplotlib - 将matplotlib中的Marker设置为带有散点图的单个像素

python - Python 中的装饰器函数

python - 减去 Pandas Dataframe 中的条目并存储在新列中

Hibernate/JPA import.sql utf8 字符损坏