Open In App

How to use unicode symbols in matplotlib?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Unicode symbols are used to enhance the visual appeal or provide additional context to plots. Unicode characters in Python are represented by code points prefixed with \u.

To render Unicode characters correctly, ensure that:

  1. The font used by Matplotlib supports the Unicode symbol.
  2. The Unicode string is prefixed with u, as in u"\u2739" for the star (*) symbol.

Methods to Use Unicode in Matplotlib

1. FontProperties Class

The FontProperties class in Matplotlib allows you to specify custom fonts for rendering text. It is important to select a font that supports the Unicode characters you want to display.

Python
import matplotlib.pyplot as plt
uni_char = u"\u2739"  # Star character

plt.text(0.5, 0.5, uni_char, fontsize=20)
plt.axis('on') 
plt.show()

Output:

Screenshot-2024-12-06-130432
star character on a plot

Unicode is a universal character encoding standard that allows computers to represent and manipulate text from various languages and symbol sets. In Python, Unicode is typically handled using UTF-8 encoding, which is compatible with most systems.

2. Using Unicode Escape Sequences

You can use Unicode escape sequences directly within your strings to represent characters. This is one of the simplest and most efficient ways to include Unicode symbols in your plots.

Python
import matplotlib.pyplot as plt
# Unicode character (Check)
uni_char = u"\u2717"  # Check Mark 

plt.text(0.5, 0.5, uni_char, fontsize=50, ha='center', va='center')
plt.axis('on') 
plt.show()

Output:

Screenshot-2024-12-06-154926
Check Mark on the Plot

3. Setting Global Font Properties

Setting global font properties in Matplotlib ensures that all text elements (titles, labels, annotations, etc.) use the specified font throughout your plots.

Python
import matplotlib.pyplot as plt
from matplotlib import rcParams

# Set global font properties
rcParams['font.family'] = 'DejaVu Sans'  # Ensure the font supports Unicode
uni_star = u"\u2739"  # Star symbol
uni_heart = u"\u2764"  # Heart symbol
uni_arrow = u"\u2192"  # Arrow symbol

plt.figure(figsize=(8, 3))

plt.text(0.3, 0.7, f"Star: {uni_star}", fontsize=20, ha='center')
plt.text(0.7, 0.7, f"Heart: {uni_heart}", fontsize=20, ha='center')
plt.text(0.5, 0.4, f"Arrow: {uni_arrow}", fontsize=25, ha='center', color='blue')

plt.title(f"Title with Unicode {uni_heart}", fontsize=18)
plt.xlabel(f"X-axis {uni_arrow}", fontsize=15)
plt.ylabel(f"Y-axis {uni_star}", fontsize=15)

plt.xlim(0, 1)
plt.ylim(0, 1)
plt.grid(True)
plt.show()

Output:

Setting-Global-Font-Properties
Setting Global Font Properties

For example, 'DejaVu Sans': Ensures all text elements (e.g., plt.text, labels, titles) use the same font that supports Unicode.


Explore