我正在嘗試使用 seaborn 熱圖繪制三角形相關矩陣,但單元格不適合注釋數字。
知道我如何讓它們很好地適合它們各自的熱圖單元嗎?
我已經嘗試過更改 figsize 并且沒有幫助。還嘗試使用 square=False。
我正在使用 seaborn==0.11.2 和 matplotlib==3.4.3
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Generate a dummy df
df = pd.DataFrame(np.random.rand(44,44))
label_lens = [16, 16, 16, 16, 16, 16, 16, 16, 20, 11,
9, 10, 10, 16, 16, 16, 16, 12, 45, 10, 10,
10, 10, 10, 10, 10, 10, 12, 12, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]
col_labels = []
for label_len in label_lens:
col_labels.append('X'*label_len)
df.columns = col_labels
# Build correlation matrix df
correlation_matrix = df.corr()
# Get Diagonal Mask. Square matrix is not relevant.
mask = np.triu(np.ones_like(correlation_matrix, dtype=bool))
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(30, 15))
# Draw the heatmap with the mask and correct aspect ratio
sns_plot = sns.heatmap(correlation_matrix,
mask=mask,
annot=True,
fmt='.2f',
square=True)
f.set_tight_layout(True)
f.savefig("my_corr_matrix.pdf")
我在這里用與實際標簽大小相同的占位符替換了我的標簽。

uj5u.com熱心網友回復:
正如評論中所指出的,使用square=Falsewithfigsize=(30, 15)解決了問題。
uj5u.com熱心網友回復:
考慮到字體大小會有點困難......你可以嘗試旋轉你的標簽,比如
plt.setp(ax.xaxis.get_majorticklabels(), rotation=25)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355918.html
標籤:Python matplotlib 海生 热图
