简体   繁体   中英

Labelling both percentages and absolute values on the cells in seaborn heatmap confusion matrix

I try to write both percentages and absolute values like " 15 (20%) " on the cells of heatmap. I can do the percentages per class via code below. But, how can I do that for both?

h_map = sns.heatmap(pyArray_cf / np.sum(pyArray_cf, axis=1),  vmin=0, vmax=1, annot=True, cmap="Blues",
                            ax=ax1, fmt='.2%',
                            mask=pyArray_cf==0,
                            xticklabels=x_axis_labels_1,
                            yticklabels=y_axis_labels_1)

Also, I would like to mask the cells with 0 values (0 times confusion).

Thanks to some of the points mentioned in the comments by Trenton, I have built the below heatmap. Hope it is what you are looking for.

  • Get the percentage of each cell using div . The percentages are calculated by dividing each cell by the sum of the whole column. Assuming that is what you require
  • Create the annotation for each cell by converting the absolute value (2 decimal places) followed by a newline character (\n) and the percentage (1 decimal place) with the % symbol in the end
  • Use annot for the text in each cell. Adjust the size and lines while creating the plot
data = np.random.rand(10, 12) #Random data 0 to 1
df = pd.DataFrame(data)

#Create perc to store the percentages for each column using DIV.
perc = df.copy()
cols=perc.columns.values
perc[cols]=perc[cols].div(perc[cols].sum(axis=1), axis=0).multiply(100)

#Use annot to store the text value to display in each cell. Number \n Percent % format
annot=df.round(2).astype(str) + "\n" + perc.round(1).astype(str) + "%"

#Create plot - adjust size, linewidth and provide annotation text for display
fig, ax = plt.subplots(figsize=(10,8))
sns.heatmap(data, annot=annot, fmt='', vmin=0, vmax=1, cmap="Blues", 
            annot_kws={"fontsize":8}, linewidth=1, ax=ax)

Plot

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM