'How to write combinations of English words and Greek letters in matplotlib?

import matplotlib.pyplot as plt
import numpy as np

x = np.array([tau for tau in range(365)])
y = np.random.normal(0,1, 365)
plt.plot(x,y)
plt.xlabel(r"$\tau$")
plt.show()

I want to use both Greek letters and regular English words in my plot title and axis labels, but I can't find in the reference of matplotlib how to write the combination of them. For example, how can I write Lag: \tau?



Solution 1:[1]

From the docs:

Any text element can use math text. You should use raw strings (precede the quotes with an 'r'), and surround the math text with dollar signs ($), as in TeX. Regular text and mathtext can be interleaved within the same string.

Therefore,

plt.xlabel(r"Lag: $\tau$")

should provide the result you're looking for.

Solution 2:[2]

You can use algebraic sum between strings. In this case your code becomes:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([tau for tau in range(365)])
y = np.random.normal(0,1, 365)
plt.plot(x,y)
plt.xlabel('Lag: ' + r'$\tau$')
plt.show()

This trick is really useful also if you want to put superscripts and/or subscripts to greek letters or latin letters

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adamgy
Solution 2 sqrt