Examples of how to plot a contingency table in python using seaborn and matplotlib:
Create a contingency table
Lets create an array:
import numpy as np
data = np.array(([78,18,4],[14,98,5],[21,12,82]))
print(data)
returns
[[78 18 4]
[14 98 5]
[21 12 82]]
Plot a contingency table
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
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.savefig("plot_contingency_table_seaborn_matplotlib_01.png", bbox_inches='tight', dpi=100)
plt.show()
Add axis labels
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()
Add 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()