7
$\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$
  • $\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
11
$\begingroup$

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

pip install matplotlib==3.1.0

https://stackoverflow.com/questions/56942670/matplotlib-seaborn-first-and-last-row-cut-in-half-of-heatmap-plot

|improve this answer|||||
$\endgroup$
3
$\begingroup$

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

ax.set_ylim([0,2])
|improve this answer|||||
$\endgroup$
2
$\begingroup$

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

For a 2*2 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))
|improve this answer|||||
$\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.