2017-02-22 33 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