2017-02-22 52 views
1

彩条的tick_labels的正确的显示我用(A版),下面的代码来生成与相邻的彩条热图:反转LogNorm为热图

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

enter image description here

由此得出的数字是如预期的,但颜色条上的蜱的标签不对应于预定的值,其应当对应于在scaled找到的值。我知道应该使用提供给FuncFormatter的函数来解决这个问题,但是目前还不清楚它应该转换哪种转换组合(或者是否使用了LogNorm这是不恰当的)。

回答

0

刚刚找到解决方案。看起来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() 

enter image description here