【发布时间】:2019-12-17 10:58:52
【问题描述】:
由于我在网上找到了不同的代码示例,我已经用 scikit-learn / matplotlib 绘制了一个混淆矩阵,但我一直在寻找如何在 xticklabels 和主标题之间添加空格。如下图所示,绘图标题和 xticklabels 重叠(+ ylabel 'True' 被剪掉了)。
Link to my confusion matrix image
这是我使用的函数:
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
PLOTS = '/plots/' # Output folder
def plt_confusion_matrix(y_test, y_pred, normalize=False, title="Confusion matrix"):
"""
Plots a nice confusion matrix.
:param y_test: list of predicted labels
:param y_pred: list of labels that should have been predicted.
:param normalize: boolean. If False, the plots shows the number of sentences predicted.
If True, shows the percentage of sentences predicted.
:param title: string. Title of the plot.
:return: Nothing but saves the plot as a PNG file and shows it.
"""
labels = list(set(y_pred))
cm = confusion_matrix(y_test, y_pred, labels)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm, cmap=plt.cm.binary, interpolation='nearest')
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig.suptitle(title, fontsize=14, wrap=True)
fig.colorbar(cax)
ax.set_xticklabels([''] + labels, rotation=45)
ax.set_yticklabels([''] + labels)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.subplots_adjust(hspace=0.6)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
plt.savefig(PLOTS + title)
plt.show()
我不得不旋转 xticklabels,因为它们太长,否则会水平重叠,而且我不得不包裹标题,因为它也太长,否则无法完全显示在图像中。
我在另一篇文章中看到 xticklabels 也可以放在图形下方(就像在this stackoverflow post 中一样),所以也许这可能是一个解决方案,但我不知道如何制作。
我该如何解决这个问题?
- 在标题和 xticklabels 之间添加一些空格 (让它们看起来完全是 btw);
- 或使 ylabel 'True' 可见
- 或移动图形下方的 xticklabels。
编辑:我尝试了两种 geekzeus 解决方案,但均未成功...
- geekzeus 的第一个解决方案的结果:See confusion matrix
- geekzeus 的第二个解决方案的结果:See confusion matrix
【问题讨论】:
标签: matplotlib plot scikit-learn axis-labels confusion-matrix