16
$\begingroup$

For some reason, my heatmap is not displaying correctly anymore. It was working just fine even with 6 classes. Since the last time I used it, I've installed many packages (including plotly). I don't know what exactly has caused this. How can I make the annotations and the x/y labels centered again? In both images the exact same code is used.

    import matplotlib.pyplot as plt
    import seaborn
    conf_mat = confusion_matrix(valid_y, y_hat)
    fig, ax = plt.subplots(figsize=(8,6))
    seaborn.heatmap(conf_mat, annot=True, fmt='d',xticklabels=classes, yticklabels=classes)
    plt.ylabel('Actual')
    plt.xlabel('Predicted')
    plt.show()

conf matrix not displaying correctly

conf matrix displayin correctly

$\endgroup$
1
  • $\begingroup$ To help you, I would need more information on the way the seaborn package is installed. How do you use the seaborn package to produce this plot? Is it via jupyter notebook? Is it in a virtual environment using anaconda? $\endgroup$ Aug 27 '19 at 16:59
15
$\begingroup$

Current version of matplotlib broke heatmaps. Downgrade the package to 3.1.0

pip install matplotlib==3.1.0

matplotlib/seaborn: first and last row cut in half of heatmap plot

$\endgroup$
7
$\begingroup$

I had the same problem, solved by moving y axis:

ax.set_ylim([0,2])
$\endgroup$
1
  • $\begingroup$ Strangely enough this work perfectly with the newer version of matplotlib. $\endgroup$ Jun 3 '20 at 1:17
2
$\begingroup$

You can work around this without downgrading, if you offset the ticks.

For a $2\times2$ matrix, this works:

fig, ax = plt.subplots()
cm = confusion_matrix(labels, predictions)

im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
ax.figure.colorbar(im, ax=ax)

ax.set(yticks=[-0.5, 1.5], 
       xticks=[0, 1], 
       yticklabels=classes, 
       xticklabels=classes)
# ax.yaxis.set_major_locator(ticker.IndexLocater(base=1, offset=0.5))
# should change to 
ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=0.5))
$\endgroup$
0
$\begingroup$

plot confusion matrix by using seaborn library

tn, fp, fn, tp = metrics.confusion_matrix(y_test,y_pred).ravel()
matrix = np.array([[tp,fp],[fn,tn]])

# plot 
sns.heatmap(matrix,annot=True, cmap="viridis" ,fmt='g')
plt.xticks([0.5,1.5],labels=[1,0])
plt.yticks([0.5,1.5],labels=[1,0])
plt.title('Confusion matrix')
plt.xlabel('Actual label')
plt.ylabel('Predicted label');
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.