Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use unicode symbols in matplotlib?

import matplotlib.pyplot as pyplot

pyplot.figure()
pyplot.xlabel(u"\u2736")
pyplot.show()

Here is the simplest code I can create to show my problem. The axis label symbol is meant to be a six-pointed star but it shows as a box. How do I change it so the star is shown? I've tried adding the comment:

#-*- coding: utf-8 -*-

like previous answers suggested but it didn't work, as well as using matplotlib.rc or matplotlib.rcParams which also didn't work. Help would be appreciated.

like image 653
Chris H Avatar asked Mar 06 '15 19:03

Chris H


People also ask

How do you use Unicode symbols in Python?

If you see utf-8 , then your system supports unicode characters. To print any character in the Python interpreter, use a \u to denote a unicode character and then follow with the character code. For instance, the code for β is 03B2, so to print β the command is print('\u03B2') .

How do I print Unicode characters in Python?

Using the \u Escape Sequence to Print Unicode Character in Python. Using the utf-8 Encoding to Print Unicode Character in Python [Python 2].

Does Python support Unicode?

Python's string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters.

How do you make a Unicode string in Python?

You have two options to create Unicode string in Python. Either use decode() , or create a new Unicode string with UTF-8 encoding by unicode(). The unicode() method is unicode(string[, encoding, errors]) , its arguments should be 8-bit strings.


1 Answers

You'll need a font that has the given unicode character, STIX fonts should contain the star symbol. You'll need to locate or download the STIX fonts, ofcourse any other ttf file with the given symbol should be fine.

import matplotlib.pyplot as pyplot
from matplotlib.font_manager import FontProperties

if __name__ == "__main__":
    pyplot.figure() 
    prop = FontProperties()
    prop.set_file('STIXGeneral.ttf')
    pyplot.xlabel(u"\u2736", fontproperties=prop)
    pyplot.show()
like image 79
arjenve Avatar answered Sep 21 '22 20:09

arjenve