2

I am aware of how to save a plot when DISPLAY is undefined:

Generating a PNG with matplotlib when DISPLAY is undefined

But when I do this with UTF-8 characters in the plot, the characters are replaced by squares in the file. Here is an example of my code:

# -*- 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')

If the 'Agg' line is commented out, the output file looks fine when DISPLAY is defined. This has happened to me both on a Mac and with CentOS. Can someone please show me how to create a jpg with the UTF characters displayed correctly when DISPLAY is undefined?

Thank you in advance!

Community
  • 1
  • 1
user3433489
  • 911
  • 2
  • 10
  • 24
  • are you sure the system you are running the code on has the correct fonts? – tacaswell Oct 27 '14 at 21:19
  • Yes. When I run it on my own computer without the 'Agg' line, the file looks perfect. But when I include the 'Agg' line, all of the letters are squares. – user3433489 Oct 27 '14 at 21:51
  • Something funny is going on with the font look up then. What interactive backend are you using? – tacaswell Oct 27 '14 at 21:52
  • and can you try specifying to use a font that you know has those glyphs? I suspect that when you start up the gui it reads your system locale and makes sure that usable fonts are set as the default where as when you use just Agg that logic doesn't get hit.... – tacaswell Oct 27 '14 at 22:01

1 Answers1

2

I think you just have to specify a usable font:

# -*- 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

You can modify the font.serif and font.sans-serif fields is rcparam to change the default font search order to put a font that has the glyphs first.

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199