Seaborn 热图,自定义刻度值

Nuk*_*las 9 python matplotlib pandas seaborn

我将 Pandas 数据框绘制为 seaborn 热图,并且我想为特定位置设置特定的 y 轴刻度。

我的数据帧索引是 100 行,对应于“深度”参数,但此索引中的值没有按良好的间隔排列: 在此处输入图片说明 我想将刻度标签设置为 100 的倍数。我可以使用以下方法很好地做到这一点:

yticks = np.linspace(10,100,10)
ylabels = np.linspace(100,1000,10)
Run Code Online (Sandbox Code Playgroud)

对于我的数据框有 100 行,值大约为 100 - 1000,但结果显然是不可取的,因为刻度标签的位置显然不对应于正确的深度值(索引),只有在指数。 在此处输入图片说明

我如何生成一个热图,其中的图是扭曲的,以便实际深度值(索引)与我设置的 ylabels 对齐?

一个复杂的因素也是索引值不是线性采样的......

liw*_*t31 9

我的解决方案有点难看,但对我有用。假设您的深度数据在depth_list并且num_ticks是您想要的刻度数:

num_ticks = 10
# the index of the position of yticks
yticks = np.linspace(0, len(depth_list) - 1, num_ticks, dtype=np.int)
# the content of labels of these yticks
yticklabels = [depth_list[idx] for idx in yticks]
Run Code Online (Sandbox Code Playgroud)

然后以这种方式绘制热图(您的数据所在的位置data):

ax = sns.heatmap(data, yticklabels=yticklabels)
ax.set_yticks(yticks)
plt.show()
Run Code Online (Sandbox Code Playgroud)


Ser*_*ity 5

使用seaborn绘图时,您必须指定热图函数的参数xticklabels和参数。在您的情况下,这些参数必须是带有自定义刻度标签的列表。yticklabels


Nuk*_*las 1

我开发了一个解决方案,可以实现我的预期,并在 liwt31 的解决方案之后进行修改:

def round(n, k):
    # function to round number 'n' up/down to nearest 'k'
    # use positive k to round up
    # use negative k to round down

    return n - n % k

# note: the df.index is a series of elevation values
tick_step = 25 
tick_min = int(round(data.index.min(), (-1 * tick_step)))  # round down
tick_max = (int(round(data.index.max(), (1 * tick_step)))) + tick_step  # round up

# the depth values for the tick labels 
# I want my y tick labels to refer to these elevations, 
# but with min and max values being a multiple of 25.
yticklabels = range(tick_min, tick_max, tick_step)
# the index position of the tick labels
yticks = []
for label in yticklabels:
    idx_pos = df.index.get_loc(label)
    yticks.append(idx_pos)

cmap = sns.color_palette("coolwarm", 128)
plt.figure(figsize=(30, 10))
ax1 = sns.heatmap(df, annot=False, cmap=cmap, yticklabels=yticklabels)
ax1.set_yticks(yticks)
plt.show()
Run Code Online (Sandbox Code Playgroud)