2

In MATLAB, if you type "\alpha" in an axis label it will render a 'plain-text' Greek character alpha, without the need for Latex. I hoping to do the same with Matplotlib's Pyplot.

Following How to use unicode symbols in matplotlib?, I've tried the following:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

if __name__ == "__main__":
    plt.figure()
    prop = FontProperties()
    prop.set_file('STIXGeneral.ttf')
    plt.xlabel(u"\u2736", fontproperties=prop)
    plt.show()

x = np.linspace(-1,1,21)

plt.figure()
plt.plot(x,x)
plt.xlabel(u"\u03b1")        # Attempt at creating an axis label with a Unicode alpha
# plt.xlabel(r'$\alpha$')     # I'm aware that Latex is possible
plt.show()

However, I get an error message with ends with

IOError: [Errno 2] No such file or directory: 'STIXGeneral.ttf'

If I omit lines 3-10, I don't get an error message but the plot shows a square instead of a Greek letter alpha:

enter image description here

Is it possible to do this with Matplotlib? (I'm aware of the possibility to display Latex, but would prefer a 'plain text' option).

Community
  • 1
  • 1
Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

1 Answers1

3

Generally, I think it is due to that your are running it in Windows, Am I right?

In Windows, you will need to specify the exact location of your font directory, instead of just the file name.

Here is what I do, after the installation of the font. I went to the control panel-> font to find the exact location of the font, which is 'C:\Windows\Fonts\STIXMath-Regular.otf' in my case. Then I just change the code to be

if __name__ == "__main__":
    plt.figure()
    prop = FontProperties(fname='C:\Windows\Fonts\STIXMath-Regular.otf')
#    prop.set_file('STIXMath-Regular.otf')
    plt.xlabel(u"\u2736", fontproperties=prop)
MaThMaX
  • 1,995
  • 1
  • 12
  • 23
  • I'm actually running Ubuntu 16.04 but found that specifying the full path of the `.ttf` file still made it work. Using the `find` command I found it was already installed at `/usr/share/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf`. – Kurt Peek Jul 07 '16 at 07:12
  • @khpeek, LOL, I thought `Linux` should be smart enough to find it even if you didn't specify any dir name! But I just went inside the source code of the `set_file()` in `matplotlib`, it looks like it is not `Linux` or `Windows`'s fault. In the source code, it didn't actually try to search anywhere so which means you have to specify the full path. – MaThMaX Jul 07 '16 at 07:16