Search code examples
pythonmatplotlibcolorbarcartopy

Bold ticklabels colorbar matplolib


To keep the colorbar aspect in subplot using cartopy, I insert new axis (add_axes) im my plot, but in adding, I need change the size of ticklabels colorbar and bold. But tick_params and set_yticklabels in not working in new axes.

# pos x,  pos y, size x, size y
cb_ax = fig.add_axes([0.91, 0.302, 0.015, 0.383])

bar = fig.colorbar(img, cax=cb_ax, extend='max',
                   shrink=0.8, pad=0.0, spacing='uniform',
                   orientation='vertical', ticks=clevs,
                   extendfrac='auto')

bar.set_label(label=f'(mm)', size=10, weight='bold')

# not working
# bar.tick_params(labelsize=10)

# not working
# bar.img.set_yticklabels(clevs, fontsize=9, weight='bold')

Entire code: https://pastebin.com/NfiMWf2n

Plot result: https://1drv.ms/u/s!Amb6LUmV4LnKi55gRf6DqGDKjfTGxA?e=HCGeZb


Solution

  • You can set the weight and fontsize of bar.ax:

    import matplotlib.pyplot as plt
    import numpy as np
    fig=plt.figure()
    img = plt.imshow(np.random.random((4,4)))
    cb_ax = fig.add_axes([0.91, 0.302, 0.015, 0.383])
    bar = fig.colorbar(img, cax=cb_ax, extend='max',
                       shrink=0.8, pad=0.0, spacing='uniform',
                       orientation='vertical',
                       extendfrac='auto')
    fig.canvas.flush_events() #else bar.ax.get_yticklabels() is not yet updated
    bar.ax.set_yticklabels(labels=bar.ax.get_yticklabels(), weight='bold', fontsize=5)
    bar.set_label(label=f'(mm)', size=10, weight='bold')
    

    Output:
    output of above example code