簡體   English   中英

Seaborn熱圖,自定義刻度值

[英]Seaborn heatmap, custom tick values

我將pandas數據框繪制到海洋熱圖,我想為特定位置設置特定的y軸刻度。

我的數據框索引是100行,對應於一個“深度”參數,但是此索引中的值沒有以適當的間隔排列: 在此處輸入圖片說明 我想將刻度標簽設置為100的倍數。我可以使用以下方法做到這一點:

yticks = np.linspace(10,100,10)
ylabels = np.linspace(100,1000,10)

對於我的具有100行的數據框,其值的范圍大約為100-1000,但是結果顯然是不可取的,因為刻度標簽的位置顯然不對應於正確的深度值(索引 ),僅對應於指數。 在此處輸入圖片說明

如何在曲線圖發生扭曲的地方生成熱圖,以使實際深度值(索引 )與我設置的ylabel對齊?

一個復雜的因素是索引值不是線性采樣的。

使用seaborn進行繪制時,必須為熱圖功能指定參數xticklabelsyticklabels 這些參數必須是帶有自定義刻度標簽的列表。

我的解決方案有點難看,但對我有用。 假設您的深度數據在depth_listnum_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]

然后以這種方式繪制熱圖(您的數據在data ):

ax = sns.heatmap(data, yticklabels=yticklabels)
ax.set_yticks(yticks)
plt.show()

我開發了一個解決方案,可以按照我的預期進行,並在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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM