Search code examples
matplotlibplotformatcolorbar

Colorbar Ticks Mathtext Format


The title is self explanatory, could not find how to implement it. For the axis ticks format similar command looks like this: ax.ticklabel_format(useMathText=True), there is no problem with this one, it works. But for the colorbar's ticks to make them appear in the MathText format I could not find how to implement it. I have tried to pass the useMathText=True as an arg into the cbar.ax.tick_params() and cbar = plt.colorbar() but that did not work.

to recreate:

import numpy as np
import matplotlib.tri as mtri
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

p = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]])
e = np.array([[0, 1, 4], [3, 0, 4], [1, 2, 4], [2, 3, 4]])
t = mtri.Triangulation(p[:, 0], p[:, 1], e)
z = np.random.rand(5)

fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
ax.set_aspect('equal', 'box')
ax.set(xlim=(min(p[:, 0]), max(p[:, 0])), ylim=(min(p[:, 1]), max(p[:, 1])))
c = ax.tricontourf(t, z, 10, cmap='plasma', vmin=np.min(z), vmax=np.max(z),
                   levels=np.linspace(np.min(z), np.max(z), 100))
ax.triplot(t, color='white', lw=0.1)
ax.set_title('Title', fontsize=16)
cbar = plt.colorbar(c, cax=cax, format='%.0e', ticks=np.linspace(np.min(z), np.max(z), 3))
cbar.set_label('Colorbar title', fontsize=16)
# cbar.ax.ticklabel_format(useMathText=True)
ax.ticklabel_format(useMathText=True)
plt.show()

Solution

  • As explained in the comments by Ernest, the colorbar for a contour gets a FixedFormatter, which doesn't accept useMathText. In my version, the code didn't give an error, but as you pointed out, also didn't generate the desired output.

    So, the answer is to change the formatter to a ScalarFormatter, and at the same time tell it to use math text. The formatter for a vertical colorbar can be set via cbar.ax.yaxis.set_major_formatter.

    from matplotlib import pyplot as plt
    from matplotlib import ticker
    import numpy as np
    
    plt.tricontourf(np.random.uniform(1, 10, 100), np.random.uniform(1, 10, 100), np.random.uniform(1e-6, 1e-5, 100))
    cbar = plt.colorbar()
    cbar.ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
    plt.show()
    

    example plot

    Please let me know whether it now works for you. (My system, now with matplotlib 3.2.1, Pycharm 2019.3.4 under Windows.)