Kurt Peek
Kurt Peek

Reputation: 57391

Use Unicode Greek letters in Matplotlib

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).

Upvotes: 2

Views: 1439

Answers (1)

MaThMaX
MaThMaX

Reputation: 2015

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)

Upvotes: 3

Related Questions