Display Greek Letters in Python Matplotlib

Display Greek Letters in Python Matplotlib

  1. Use the Raw Strings and $ Sign to Show Greek Letters With matplotlib in Python
  2. Use the chr() Function to Show Greek Letters With matplotlib in Python
  3. Use the Literal Strings to Show Greek Letters With matplotlib in Python

The matplotlib package in Python creates beautiful graphs and statistical plots. We can customize the graphs with relevant labels, titles, and legends.

We can have plots representing some mathematical or statistical equations. We can add relevant information using the plot title or axis labels.

The matplotlib package can also represent Greek letters. This tutorial will teach how to write these letters on labels and titles.

Use the Raw Strings and $ Sign to Show Greek Letters With matplotlib in Python

The matplotlib has an integrated expression parser and layout engine.

For this, we need to use raw strings, which means adding the r character before a string. We need to enclose different Greek letters using the $ sign in these raw strings with their names to represent different Greek letters.

For example,

import matplotlib.pyplot as plt
plt.title(r'$\alpha$')

Output:

raw strings to show greek letters

We can also add multiple letters and work them between strings by maintaining their order using the square brackets.

See the example below.

import matplotlib.pyplot as plt
plt.title(r'Str [$\mu \alpha$]')

greek letters using raw string

Use the chr() Function to Show Greek Letters With matplotlib in Python

Greek letters are encoded in Unicode. In Python 3, the small Greek letters are coded.

They start from 945 to 969. We can use the chr() function to encode the character in integers.

We can add them to matplotlib plots and figures.

For example,

import matplotlib.pyplot as plt
plt.title(chr(945))

Output:

chr function to show greek letters

Use the Literal Strings to Show Greek Letters With matplotlib in Python

We can directly use the Greek letters in Python 3 and above. These can be used with matplotlib plots as well.

For example,

import matplotlib.pyplot as plt
plt.title('α')

literal string to show greek letters

In Python 2, we can use the same by first importing the unicode_literals from the __future__ module.

For example,

from __future__ import unicode_literals
import matplotlib.pyplot as plt
plt.title('α')
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn