考虑下图(生成它的代码在下面):

python - 在颜色栏中偏移刻度线标签-LMLPHP

上方的刻度标签(9.5E-05)看起来不错,但是我希望底部和中间的刻度标签垂直向上对齐(注意,这两个标签均没有相同的对齐方式),因此它们看起来像这样:

python - 在颜色栏中偏移刻度线标签-LMLPHP

看起来好多了(至少对我来说)。我一直在环顾四周,但没有找到一种方法来做到这一点。



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


ax = plt.subplot(111)
data = np.random.uniform(0., 10., (50, 50))
im = plt.imshow(data)

# Colorbar on the right side of ax.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.05)
cbar = plt.colorbar(im, cax=cax)
cbar.set_ticks([np.min(data), np.ptp(data) * .5, np.max(data)])
print(np.min(data), np.ptp(data) * .5, np.max(data))

cbar.ax.set_yticklabels([
    '{:.1E}'.format(0.00000133),
    '{:.1E}'.format(0.00000561),
    '{:.1E}'.format(0.0000948)], rotation=90)

plt.show()

最佳答案

您可以遍历颜色栏的y刻度标签,并根据其标签设置文本的垂直对齐方式。

# don't include last label (one at the top) as we don't want to change its alignment
for i, label in enumerate(cbar.ax.get_yticklabels()[:-1]):
    if i == 0:  # first label
        label.set_va("bottom")
    else:
        label.set_va("center")


python - 在颜色栏中偏移刻度线标签-LMLPHP

关于python - 在颜色栏中偏移刻度线标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56062626/

10-12 16:50
查看更多