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)

conf matrix not displaying correctly

conf matrix displayin correctly

  • $\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$ – Dr. H. Lecter Aug 27 '19 at 16:59

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

| improve this answer | |

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

| improve this answer | |
  • $\begingroup$ Strangely enough this work perfectly with the newer version of matplotlib. $\endgroup$ – Yacine Mahdid Jun 3 at 1:17

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], 
# 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))
| improve this answer | |

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.title('Confusion matrix')
plt.xlabel('Actual label')
plt.ylabel('Predicted label');
| improve this answer | |

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.