0

In my code below, I use

import mplcursors
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

from sklearn.metrics import confusion_matrix

labels_true = [1,2,3,4,5,6]
labels_pred = [1,2,3,1,2,3]

# confusion_matrix
cm = confusion_matrix(labels_true, labels_pred, normalize='true')

# dataframe
df_cm = pd.DataFrame(cm)

followed by either

# option 1:
sns.heatmap(df_cm, annot=True, linewidths=1, cmap="Blues_r",xticklabels=2, square=True)

or, alternatively

# option 2:
plt.imshow(df_cm)

followed by

# clickable cells
# cursor = mplcursors.cursor(heatmap, hover=False)
cursor = mplcursors.cursor(hover=False)

@cursor.connect("add")
def on_add(sel):
    i,j = sel.target.index
    text = 'Test message!'
    sel.annotation.set_text(text)

plt.show()

When I use option 1, I get thisenter image description here, which has a plus, that the cells each have a number label on them; but also has a minus, that the cells are not clickable.

When I use option 2, I get thisenter image description here, which has a plus, that I can click the cells; but has a minus, that I cannot see the number labeled on each cell.

Isn't there a way I can get the best of both worlds? I want numbers on the cells AND clickable cells. Thanks!

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
yishairasowsky
  • 741
  • 1
  • 7
  • 21
  • Maybe you could set the ticks at 0.5, 1.5, 2.5, ... instead of at 0, 1, 2, ...? – JohanC Jan 22 '20 at 15:07
  • First off, do not plot a `sns.heatmap` and a `plt.imshow` at the same time. Decide for one of those, delete the other. Then depending on which one you choose, you will need to put the ticks at half integer position (for seaborn heatmap), or at full integer positions (for matplotlib imshow). – ImportanceOfBeingErnest Jan 22 '20 at 15:15
  • @JohanC how do i do that? – yishairasowsky Jan 22 '20 at 15:16
  • I do not understand which features you need. Please edit the question to include that. Also, providing a [mcve] would increase the chances of getting an actual answer here, once the above is clarified. – ImportanceOfBeingErnest Jan 22 '20 at 16:03
  • @yishairasowsky: Maybe `plt.xticks([i+0.5 for i in range(len(pred_spectrum))], pred_spectrum)` or use `np.arange`? Please do take IOBE's advice into account. Choose between `sns.heatmap` and `plt.imshow` and provide code for an example independent of external data. – JohanC Jan 22 '20 at 16:33
  • To add the labels, here is an [answer](https://stackoverflow.com/questions/59810130/how-to-add-tooltips-to-a-confusion-matrix-rendered-via-a-seaborn-heatmap/59823777#59823777) from a few days ago containing a matrix displayed with `imshow`, labels added at the cell centers and an `mplcursor` showing additional information. – JohanC Jan 24 '20 at 06:39

0 Answers0