我正在尝试使用下面的数组绘制混淆矩阵。然而,当热图呈现时,列和轴标签从绘图 View 中流出,我无法弄清楚如何控制这种格式。似乎我需要一种方法来设置一些填充值。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
array = [
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0],
[0,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[0,0,0,0,3,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0],
[0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
[0,1,0,1,0,0,0,6,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,3,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,7,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,1,4,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,1,1,0,0,0,0],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,38,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,8,0,0,0,1],
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9]]
labels = ['chatbot',
'business_passwordreset',
'business_losthomework',
'oos_generic',
'frustration',
'social_generic',
'business_accesscode_selfstudy',
'business_assignmentissues',
'end_chat',
'bye',
'thanks',
'business_accesscode_lost',
'business_accesscode_redeem',
'business_accesscode_notreceived',
'business_accesscode_share',
'business_accesscode_reuse',
'business_editorial',
'Contact_Request',
'business_accesscode_error',
'business_accesscode_refund',
'hello',
'business_accesscode_purchase',
'business_accesscode_troubleshoot']
df_cm = pd.DataFrame(array, index=labels, columns=labels)
sn.heatmap(df_cm, annot=True, cmap='Blues')
plt.show()
其他一切看起来都很好,但如果能够阅读标签就好了!有人知道我错过了什么吗?
最佳答案
你的标签真的很长,所以我认为你最好的办法是创建一个大数字,然后使用 plt.tight_layout
.如文档中所述:
This module provides routines to adjust subplot params so that subplots are nicely fit in the figure
# Create a large figure so your labels aren't too crowded
plt.figure(figsize=(13,7))
df_cm = pd.DataFrame(array, index=labels, columns=labels)
sn.heatmap(df_cm, annot=True, cmap='Blues')
plt.tight_layout()
plt.show()
关于python - 防止轴和列标签在 matplotlib 中流出热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51351129/