You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Seaborn中设置热力图的x_ticks?解决自定义x轴刻度不生效问题

Fixing X-Ticks on Seaborn Heatmap: From 0.01-1.01 to 0.1-1.0

Hey there! I get why your set_xticks call isn't working—let's break this down and fix it step by step.

Why Your Current Code Fails

When you create a heatmap with seaborn, the x-axis uses position indices (0 to 99 in your case, since you have 100 columns) under the hood, not the actual column labels (0.01 to 1.01). So when you try to set ticks to [0.1, 0.2, ...], matplotlib is looking for positions at those numeric values, which don't exist in your axis range (0-99). That's why nothing changes!

The Solution

We need to:

  1. Define the position indices that correspond to your desired tick labels (0.1, 0.2, ..., 1.0)
  2. Set those positions with set_xticks
  3. Assign your custom labels with set_xticklabels

Here's the modified code that works:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# Original setup
colums = np.arange(0.01, 1.01, 0.01)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 100)), columns=colums.tolist())
ax1 = sns.heatmap(df, vmin=0., vmax=1, linewidths=.05, cbar_kws={'label': '?'})

# Customize x-ticks
new_xtick_labels = np.arange(0.1, 1.1, 0.1)  # [0.1, 0.2, ..., 1.0]
# Calculate positions: 0.1 is at index 9, 0.2 at 19, ..., 1.0 at 99
new_xtick_positions = np.arange(9, 100, 10)  

# Apply the ticks and labels
ax1.set_xticks(new_xtick_positions)
ax1.set_xticklabels(new_xtick_labels.round(1))  # Round to 1 decimal for clean display

plt.show()

A More Flexible Approach

If your column range or step size ever changes, you can dynamically find the positions of your desired labels instead of hardcoding them:

new_xtick_labels = np.arange(0.1, 1.1, 0.1)
# Find indices where column values match your target labels (handles floating-point precision)
new_xtick_positions = [np.where(np.isclose(colums, tick))[0][0] for tick in new_xtick_labels]

ax1.set_xticks(new_xtick_positions)
ax1.set_xticklabels(new_xtick_labels)

内容的提问来源于stack exchange,提问作者W.D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:32:32