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$ Commented Aug 27, 2019 at 16:59

4 Answers 4


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


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

  • $\begingroup$ Strangely enough this work perfectly with the newer version of matplotlib. $\endgroup$ Commented Jun 3, 2020 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))

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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