Search code examples
pythonmatplotlibplotf-string

Build a LaTeX label programmatically in matplotlib


I can render hardcoded LaTeX expressions in matplotlib labels, no problem:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0., 2.* np.pi, 20)
y = 2. * np.pi * np.stack((np.sin(x), np.cos(x)))

fig, ax = plt.subplots(2, 1, figsize=(6, 8), dpi=200, constrained_layout=True)

i=0
current_ax = ax[i]
current_ax.plot(x, y[i, :], '--.k', markersize=5, alpha=0.5)
current_ax.set_xlabel('x')
current_ax.set_ylabel(r'$2\pi*\sin (x)$')

i=1
current_ax = ax[i]
current_ax.plot(x, y[i, :], '--.k', markersize=5, alpha=0.5)
current_ax.set_xlabel('x')
current_ax.set_ylabel(r'$2\pi*\cos (x)$')

plt.show()

However, I would like to be able to build them programmatically. In other words, I would like to be able to define a string label such as

function = 'sin'
my_label = f"r'$2\pi*\{function} (x)$'"
current_ax.set_ylabel(my_label)

However, this doesn't seem to work. Is there a way to fix it?


Solution

  • I think you intended to use both raw string(r) and f-string(f) together. If that's the case you have to prefix your string with rf(or fr).

    >>> function = 'sin'
    >>> my_label = rf"$2\pi*\{function} (x)$"
    >>> my_label
    '$2\\pi*\\sin (x)$'