seaborn 热图的人工刻度标签

Artificial tick labels for seaborn heatmaps

我有一个如下所示的 seaborn 热图:

...从随机生成值的 pandas 数据帧生成,其中一部分看起来像这样:

y轴的值都在[0,1]范围内,x轴的值在[0,2*pi]范围内,我只是想要一些固定时间间隔的短浮点数对于我的刻度标签,但我似乎只能获得数据框中的值。当我尝试指定我想要的值时,它没有将它们放在正确的位置,如上图所示。他现在是我的代号。我怎样才能在正确的位置获得我尝试用 xticks 和 yticks 在这段代码中指定的轴标签(这将沿着轴均匀分布)?

import pandas as pd
import numpy as np
import matplotlib as plt
from matplotlib.mlab import griddata

sns.set_style("darkgrid")
PHI, COSTH = np.meshgrid(phis, cos_thetas)
THICK = griddata(phis, cos_thetas, thicknesses, PHI, COSTH, interp='linear')

thick_df = pd.DataFrame(THICK, columns=phis, index=cos_thetas)
thick_df = thick_df.sort_index(axis=0, ascending=False)
thick_df = thick_df.sort_index(axis=1)

cmap = sns.cubehelix_palette(start=1.6, light=0.8, as_cmap=True, reverse=True)

yticks = np.array([0,0.2,0.4,0.6,0.8,1.0])

xticks = np.array([0,1,2,3,4,5,6])

g = sns.heatmap(thick_df, linewidth=0, xticklabels=xticks, yticklabels=yticks, square=True, cmap=cmap)

plt.show(g)

这里有一些东西可以满足您的需求:

cmap = sns.cubehelix_palette(start=1.6, light=0.8, as_cmap=True, reverse=True)

yticks = np.linspace(0,1,6)

x_end = 6
xticks = np.arange(x_end+1)

ax = sns.heatmap(thick_df, linewidth=0, xticklabels=xticks, yticklabels=yticks[::-1], square=True, cmap=cmap)

ax.set_xticks(xticks*ax.get_xlim()[1]/(2*math.pi))
ax.set_yticks(yticks*ax.get_ylim()[1])

plt.show()

您可以传递 ['{:,.2f}'.format(x) for x in xticks] 而不是 xticks 以获得带 2 位小数的浮点数。

请注意,我正在反转 yticklabels,因为这就是 seaborn 所做的:请参阅 matrix.py#L138

Seaborn 计算同一位置附近的刻度位置(例如:#L148),对您而言,这相当于:

# thick_df.T.shape[0] = thick_df.shape[1]
xticks: np.arange(0, thick_df.T.shape[0], 1) + .5
yticks: np.arange(0, thick_df.T.shape[1], 1) + .5