pythonmatplotliblatexrenderingcolorbar

Issue with LaTeX rendering in the title of colorbar plots using Python's Matplotlib library


I am facing an issue with the title of the following colorbar plots using Python's Matplotlib library. There are two subplots. The title of the first one works well, i.e., LaTeX rendering is done successfully. However, it returns an error for the second one.

fig, axs = plt.subplots(1, 2, figsize=(24, 10))
    
    
c1 = axs[0].contourf(x, y, zT, 60, cmap='seismic', vmin=-2.5, vmax=2.5)
axs[0].set_title(r'$\zeta_T$ at t={}'.format(l))
fig.colorbar(c1, ax=axs[0])

    
c2 = axs[1].contourf(x, y, bcv, 40, cmap='seismic', vmin=-0.25, vmax=0.25)
axs[1].set_title(r'$\sqrt{U_c^2 + V_c^2}$ at t={}'.format(l))
fig.colorbar(c2, ax=axs[1])

The error is as follows:

KeyError                                  Traceback (most recent call last)
Cell In[27], line 80
     79 c2 = axs[1].contourf(x, y, bcv, 40, cmap='seismic', vmin=-0.25, vmax=0.25)
---> 80 axs[1].set_title(r'$\sqrt{U_c^2 + V_c^2}$ at t={}'.format(l)) 
     81 fig.colorbar(c2, ax=axs[1])

KeyError: 'U_c^2 + V_c^2'

I wonder why the LaTeX command $\sqrt{U_c^2+V_c^2}$ does not work in the title. Why is the LaTeX rendering not working in Matplotlib?

I tried to fix it in several ways, but I consistently get that "KeyError". I used plt.rc('text', usetex=True) to enable LaTeX rendering in Matplotlib. But it did not work either. I want to fix this LaTeX rendering issue in Matplotlib.


Solution

  • This is LaTeX syntax clashing with function of pythons .format() method. The latter looks for curly brackets {...} in the string and operates on them, but there are two sets of curly brackets in

        r'$\sqrt{U_c^2 + V_c^2}$ at t={}'
    

    and the first contains something that does not fit with the .format() syntax.

    I suggest you split this up as two strings, with just the format method on the second one

        r'$\sqrt{U_c^2 + V_c^2}$ ' + 'at t={}'.format(l)
    

    Here is a complete working example of similar character (I don't have your data).

    import matplotlib.pyplot as plt
    import numpy as np
    plt.rc('text', usetex=True)
    
    x = np.linspace(-np.pi, np.pi, 100)
    t = 3.0
    
    fig, ax = plt.subplots()
    ax.plot(x, np.sqrt(x**2+1))
    ax.set_title(r'$\sqrt{x^2 + 1}$' + ' at {}'.format(t))
    

    Sample output