Exemples de comment tracer une table de contingence (heatmap) en python avec seaborn et matplotlib
Créer une table de contingence
import numpy as npdata = np.array(([78,18,4],[14,98,5],[21,12,82]))print(data)
donne
[[78 18 4][14 98 5][21 12 82]]
Tracez un tableau de contingence
import seaborn as sns; sns.set()import matplotlib.pyplot as pltfig = plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')plt.clf()ax = fig.add_subplot(111)ax.set_aspect(1)res = sns.heatmap(data, annot=True, fmt='.2f', cmap="YlGnBu", vmin=0.0, vmax=100.0)plt.title('How to plot a coningency table with python \n using matplotlib and seaborn ?',fontsize=12)plt.savefig("plot_contingency_table_seaborn_matplotlib_01.png", bbox_inches='tight', dpi=100)plt.show()

Ajouter des labels sur les axes
fig = plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')plt.clf()ax = fig.add_subplot(111)ax.set_aspect(1)res = sns.heatmap(data, annot=True, fmt='.2f', cmap="YlGnBu", vmin=0.0, vmax=100.0)plt.title('How to plot a coningency table with python \n using matplotlib and seaborn ?',fontsize=12)plt.xticks([i+0.5 for i in range(data.shape[0])], ['A1', 'B1', 'C1'])plt.xticks(rotation=0)plt.yticks([i+0.5 for i in range(data.shape[1])], ['A2', 'B2', 'C2'])plt.yticks(rotation=0)plt.savefig("plot_contingency_table_seaborn_matplotlib_02.png", bbox_inches='tight', dpi=100)plt.show()

Ajouter des annotations
fig = plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')plt.clf()ax = fig.add_subplot(111)ax.set_aspect(1)annot_m = np.empty(data.shape,dtype='<U16')for i in range(data.shape[0]):for j in range(data.shape[0]):annot_m[i,j] = 'Score: {}'.format(data[i,j])res = sns.heatmap(data, annot=annot_m, fmt="", cmap="YlGnBu", vmin=0.0, vmax=100.0)plt.title('How to plot a coningency table with python \n using matplotlib and seaborn ?',fontsize=12)plt.xticks([i+0.5 for i in range(data.shape[0])], ['A1', 'B1', 'C1'])plt.xticks(rotation=0)plt.yticks([i+0.5 for i in range(data.shape[1])], ['A2', 'B2', 'C2'])plt.yticks(rotation=0)plt.yticks(rotation=0)plt.savefig("plot_contingency_table_seaborn_matplotlib_03.png", bbox_inches='tight', dpi=100)plt.show()

