简体   繁体   中英

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:

在此处输入图片说明

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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