简体   繁体   中英

Rotation of colorbar tick labels in matplotlib resets tick label formatting

If I do rotation to the colorbar labels, the format I used seem to be reset (ignored).

The fig.colorbar does not accept rotation, while cb.ax.set_xticklabels does not accept format. I couldn't find any way to do both settings.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter

test = np.random.rand(100, 100)
np.random.seed(12345)

fig, axs = plt.subplots(1, 2, figsize=(6, 5))
fmts = ["%d", "%.5f"]

for i, ax in enumerate(axs.tolist()):
    im = ax.imshow(test, origin="lower")
    cb = fig.colorbar(im, ax=ax, orientation='horizontal', 
                      format=FormatStrFormatter(fmts[i]))
    ax.set_title(f"Format {fmts[i]}")

    cb.ax.set_xticklabels(cb.get_ticks(), rotation=45)

plt.tight_layout()
plt.show()

The colorbar tick labels should be in the format of "%d" and "%.5f" but as you can see, neither does.

I don't think that the original formatting is kept when you call cb.ax.set_xticklabels() , you could add cb.ax.xaxis.set_major_formatter(FormatStrFormatter(fmts[i])) to re-apply the custom formatting afterwards.

As an alternative, use plt.setp(cb.ax.get_xticklabels(),rotation=45) instead to rotate the labels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM