简体   繁体   English

matplotlib显示有效,而savefig对于Unicode失败

[英]matplotlib show works while savefig fails for unicode

The following code produces the correct plot with plt.show() but fails when saved into a pdf or png image. 以下代码使用plt.show()生成正确的图,但是将其保存到pdf或png图像时会失败。

I have tried various suggestions (see commented lines) in similar questions, but none of them works for this case. 我曾在类似的问题中尝试过各种建议(请参见注释行),但是这些建议均不适用于这种情况。 Png file shows the unicode characters as boxes while pdf simply ignores them. Png文件将unicode字符显示为框,而pdf只是忽略它们。

##-*- coding: utf-8 -*-
#from matplotlib import rc
#rc('font', **font)
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
#rc('font',**{'family':'serif','serif':['Palatino']})
#rc('text', usetex=True)
import matplotlib.pyplot as plt

plt.figure()
plt.plot(range(10))
plt.xlabel(u"\u2736")
plt.ylabel(u'\u03c4') 
plt.savefig('unicode.pdf')
plt.savefig('unicode.png')
#plt.show()

You were nearly there when you tried changing the font family. 当您尝试更改字体系列时,您已经快到了。

Only certain fonts support unicode characters. 仅某些字体支持Unicode字符。 You can check which fonts you have installed via: 您可以通过以下方法检查已安装的字体:

import matplotlib.font_manager as fm
set([f.name for f in fm.fontManager.ttflist])

Then change to a unicode font, eg DejaVu Sans in Linux, Arial Unicode MS for Windows, Lucida Grande for Mac OS X, more on Wiki . 然后更改为unicode字体,例如Linux中的DejaVu Sans ,Windows中的Arial Unicode MS ,Mac OS X中的Lucida Grande ,以及更多Wiki No need to use tex: 无需使用tex:

plt.rcParams['font.family'] = 'DejaVu Sans'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM