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

时间:2019-05-09 15:16:58

标签: python matplotlib colorbar

请考虑以下图片(生成该图片的代码如下):

enter image description here

上方的刻度标签(9.5E-05)看起来不错,但我希望底部和中间的刻度标签垂直向上对齐(请注意, ),使它们看起来像这样:

enter image description here

看起来更好(至少对我而言)。我一直在环顾四周,但还没有找到一种方法。


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()

1 个答案:

答案 0 :(得分:1)

您可以遍历颜色栏的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")

enter image description here