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

如何去除相关图顶部空白、添加刻度并保留两位相关系数

Solution to Your Seaborn Heatmap Issues

Let's tackle each of your three problems one by one and fix the code step by step:

1. Remove Top White Space

The issue with plt.tight_layout(pad=0) and subplots_adjust likely stems from the title pushing the top margin. We can adjust the figure's top margin directly and combine it with tight layout to eliminate extra space effectively.

2. Show Axis Ticks

Your sns.set_style call had incorrect syntax—you need to pass a single dictionary of parameters instead of two separate ones. We'll also add an explicit tick enablement as a safeguard to ensure they show up.

3. Limit Correlation Coefficients to 2 Decimal Places

Use the fmt=".2f" parameter in sns.heatmap to format the annotation text to exactly two decimal places.

Modified Full Code

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

# Set style BEFORE plotting to ensure tick settings take effect
sns.set_style("white", {'xtick.bottom': True, 'ytick.left': True})

corr = by_profit.T.corr()
mask = np.triu(np.ones_like(corr, dtype=np.bool))

f, ax = plt.subplots(figsize=(10, 9), dpi=100)

# Add fmt=".2f" to format annotations to 2 decimal places
sns.heatmap(corr, 
            mask=mask, 
            cmap='coolwarm', 
            vmax=1, 
            vmin=-1,
            center=0, 
            square=True, 
            linewidths=.5, 
            cbar_kws={"shrink": .5},
            annot=True, 
            annot_kws={"size": 9},
            fmt=".2f")  # Controls decimal place formatting

ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right')

# Explicitly enable ticks as an extra safeguard
ax.tick_params(axis='x', bottom=True)
ax.tick_params(axis='y', left=True)

plt.title('Correlation Between Sub-Category Sales')
plt.xlabel('')
plt.ylabel('')

# Adjust margins to remove top white space - tweak values if needed
plt.subplots_adjust(top=0.98, bottom=0.12, left=0.1, right=0.9)
plt.tight_layout(pad=0)

plt.show()

Key Explanations:

  • Top Space Fix: plt.subplots_adjust(top=0.98) reduces the top margin to push the heatmap upward, while plt.tight_layout(pad=0) ensures no unnecessary padding around plot elements.
  • Ticks Fix: sns.set_style("white", {'xtick.bottom': True, 'ytick.left': True}) correctly passes tick settings in a single dictionary. Adding ax.tick_params ensures ticks are explicitly enabled, even if style settings are overridden elsewhere.
  • Decimal Places: The fmt=".2f" argument in sns.heatmap tells the annotation formatter to display correlation coefficients with exactly two decimal places.

内容的提问来源于stack exchange,提问作者flyunicorn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:57:52