![](/img/trans.png)
[英]Mirror the color scale of a Seaborn heatmap, both colors and labels
[英]seaborn heatmap auto-ordering labels to smoothen color shifts
第二個圖由x和y軸標簽排序,而不是值。 您將無法使隨機數據看起來像有序數據。 您可以按一行和一列的值對數據進行排序,但其余數據將被修復。 下面是繪制按行0和列0的值排序的熱圖的代碼。請注意圖中間的“交叉”:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
df = pd.DataFrame(uniform_data)
df2 = df.sort_values(by=0).T.sort_values(by=0).T
ax = sns.heatmap(df2)
人們需要以某種方式量化“平滑的色彩提升”。 為此目的,可以定義成本函數。 在最簡單的情況下,這可以是相鄰像素之間的差異的總和。 如果該總和很小,則相鄰像素的顏色差異很小。
然后可以隨機交換矩陣中的列和行,並檢查是否產生較小的成本。 迭代地執行此操作,在某些時候會產生平滑的熱圖。 然而,它當然將取決於初始熱圖中的隨機程度。 對於完全隨機的像素,可以預期不會進行太多的優化。
以下類實現此類優化。 這將需要nrand
不同的出發排列和每個,做交換niter
倍。 存儲的最佳結果可以通過.get_opt
檢索。
import matplotlib.pyplot as plt
import numpy as np
class ReOrder():
def __init__(self, array, nrand=2, niter=800):
self.a = array
self.indi = np.arange(self.a.shape[0])
self.indj = np.arange(self.a.shape[1])
self.i = np.arange(self.a.shape[0])
self.j = np.arange(self.a.shape[1])
self.nrand = nrand
self.niter = niter
def apply(self, a, i, j):
return a[:,j][i,:]
def get_opt(self):
return self.apply(self.a, self.i, self.j)
def get_labels(self, x=None, y=None):
if x is None:
x = self.indj
if y is None:
y = self.indi
return np.array(x)[self.j], np.array(y)[self.i]
def cost(self, a=None):
if a is None:
a = self.get_opt()
m = a[1:-1, 1:-1]
b = 0.5 * ((m - a[0:-2, 0:-2])**2 + \
(m - a[2: , 2: ])**2 + \
(m - a[0:-2, 2: ])**2 + \
(m - a[2: , 0:-2])**2) + \
(m - a[0:-2, 1:-1])**2 + \
(m - a[1:-1, 0:-2])**2 + \
(m - a[2: , 1:-1])**2 + \
(m - a[1:-1, 2: ])**2
return b.sum()
def randomize(self):
newj = np.random.permutation(self.a.shape[1])
newi = np.random.permutation(self.a.shape[0])
return newi, newj
def compare(self, i1, j1, i2, j2, a=None):
if a is None:
a = self.a
if self.cost(self.apply(a,i1,j1)) < self.cost(self.apply(a,i2,j2)):
return i1, j1
else:
return i2, j2
def rowswap(self, i, j):
rows = np.random.choice(self.indi, replace=False, size=2)
ir = np.copy(i)
ir[rows] = ir[rows[::-1]]
return ir, j
def colswap(self, i, j):
cols = np.random.choice(self.indj, replace=False, size=2)
jr = np.copy(j)
jr[cols] = jr[cols[::-1]]
return i, jr
def swap(self, i, j):
ic, jc = self.rowswap(i,j)
ir, jr = self.colswap(i,j)
io, jo = self.compare(ic,jc, ir,jr)
return self.compare(i,j, io,jo)
def optimize(self, nrand=None, niter=None):
nrand = nrand or self.nrand
niter = niter or self.niter
i,j = self.i, self.j
for kk in range(niter):
i,j = self.swap(i,j)
self.i, self.j = self.compare(i,j, self.i, self.j)
print(self.cost())
for ii in range(nrand):
i,j = self.randomize()
for kk in range(niter):
i,j = self.swap(i,j)
self.i, self.j = self.compare(i,j, self.i, self.j)
print(self.cost())
print("finished")
那么我們來看兩個起始陣列,
def get_sample_ord():
x,y = np.meshgrid(np.arange(12), np.arange(10))
z = x+y
j = np.random.permutation(12)
i = np.random.permutation(10)
return z[:,j][i,:]
def get_sample():
return np.random.randint(0,120,size=(10,12))
並通過上面的類運行它。
def reorder_plot(nrand=4, niter=10000):
fig, ((ax1, ax2),(ax3,ax4)) = plt.subplots(nrows=2, ncols=2,
constrained_layout=True)
fig.suptitle("nrand={}, niter={}".format(nrand, niter))
z1 = get_sample()
r1 = ReOrder(z1)
r1.optimize(nrand=nrand, niter=niter)
ax1.imshow(z1)
ax3.imshow(r1.get_opt())
xl, yl = r1.get_labels()
ax1.set(xticks = np.arange(z1.shape[1]),
yticks = np.arange(z1.shape[0]),
title=f"Start, cost={r1.cost(z1)}")
ax3.set(xticks = np.arange(z1.shape[1]), xticklabels=xl,
yticks = np.arange(z1.shape[0]), yticklabels=yl,
title=f"Optimized, cost={r1.cost()}")
z2 = get_sample_ord()
r2 = ReOrder(z2)
r2.optimize(nrand=nrand, niter=niter)
ax2.imshow(z2)
ax4.imshow(r2.get_opt())
xl, yl = r2.get_labels()
ax2.set(xticks = np.arange(z2.shape[1]),
yticks = np.arange(z2.shape[0]),
title=f"Start, cost={r2.cost(z2)}")
ax4.set(xticks = np.arange(z2.shape[1]), xticklabels=xl,
yticks = np.arange(z2.shape[0]), yticklabels=yl,
title=f"Optimized, cost={r2.cost()}")
reorder_plot(nrand=4, niter=10000)
plt.show()
完全隨機的矩陣(左列)只是非常平滑 - 仍然看起來更加分類。 成本值仍然相當高。 然而,不那么隨機的矩陣被完美地平滑並且成本顯着降低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.