我使用以下代码(的一个版本)来生成带有相邻色条的热图:

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

# create some dummy-data
matrix = np.array([[1, 2, 3],[2, 1, 3], [3, 1, 2]])
# scale the data
scaled = matrix / matrix.sum(axis=1).reshape(-1,1)


这是scaled的样子(在此示例中,缩放没有区别,但在将缩放的数据用于层次结构链接的预期用例中确实如此):

array([[ 0.16666667,  0.33333333,  0.5       ],
   [ 0.33333333,  0.16666667,  0.5       ],
   [ 0.5       ,  0.16666667,  0.33333333]])


现在创建图(注意使用LogNorm):

_, ax_heatmap = plt.subplots()
heatmap = ax_heatmap.pcolor(
    scaled, edgecolors='w',
    cmap=mpl.cm.viridis_r,
    norm=mpl.colors.LogNorm())
ax_heatmap.autoscale(tight=True)
ax_heatmap.set_aspect('equal')
divider_h = make_axes_locatable(ax_heatmap)
cax = divider_h.append_axes("right", "3%", pad="1%")
plt.colorbar(heatmap, cax=cax, ticks=np.unique(scaled))
cax.yaxis.set_major_formatter(
        mpl.ticker.FuncFormatter(
            lambda y, pos: ('{:.1f}'.format(y))))
plt.tight_layout()
plt.show()


python - 反转LogNorm以正确显示热图颜色栏的tick_labels-LMLPHP

结果数字符合预期,但彩条上的刻度标签与预期值不对应,预期值应与scaled中的值对应。我知道应该使用提供给FuncFormatter的函数来解决此问题,但是目前尚不清楚应该反转哪个转换组合(或者是否不合适使用LogNorm)。

最佳答案

刚刚找到解决方案。看来LogNorm具有逆方法。通过首先使用正确的vmin和vmax初始化LogNorm对象,可以将其逆提供给FuncFormatter

_, ax_heatmap = plt.subplots()
norm = mpl.colors.LogNorm(vmin=scaled.min(), vmax=scaled.max())
heatmap = ax_heatmap.pcolor(
    scaled, edgecolors='w',
    cmap=mpl.cm.viridis_r,
    norm=norm)
ax_heatmap.autoscale(tight=True)
ax_heatmap.set_aspect('equal')
divider_h = make_axes_locatable(ax_heatmap)
cax = divider_h.append_axes("right", "3%", pad="1%")
plt.colorbar(heatmap, cax=cax, ticks=np.unique(scaled))
cax.yaxis.set_major_formatter(
        mpl.ticker.FuncFormatter(
            lambda y, pos: ('{:.5f}'.format(norm.inverse(y)))))
plt.tight_layout()
plt.show()


python - 反转LogNorm以正确显示热图颜色栏的tick_labels-LMLPHP

08-04 17:50