Muhammad
Muhammad

Reputation: 129

Plot Confusion Matrix with custom x and y axis in Python?

I have confusion matrix in form of an array like

[[ 265, 1522],
 [  44,  146]]

I am doing something like this to plot

import seaborn as sns
import matplotlib.pyplot as plt
cm = confusion_matrix(yTest, yPredicted)
sns.heatmap(cm, annot=True,fmt="d", cmap='YlGnBu', linecolor='black', linewidths=1)
plt.title("Confusion Matrix")
plt.title("Confusion Matrix")
plt.xlabel("Actual")
plt.ylabel("Predicted")

andit is giving me this graph

But How can i change x and y axsis and get graph like that Required Graph

Upvotes: 0

Views: 1662

Answers (1)

Stef
Stef

Reputation: 30639

Transpose the matrix, swap the axis labels and reverse the axis directions by setting the limits:

sns.heatmap(cm.T, annot=True,fmt="d", cmap='YlGnBu', linecolor='black', linewidths=1)
plt.title("Confusion Matrix")
plt.ylabel("Actual")
plt.xlabel("Predicted")
plt.ylim(0,2)
plt.xlim(2,0)

You can rotate y axis labels as shown in your example like that:

plt.ylabel('\n'.join(list('Actual')), rotation=0, va='center')
plt.yticks(rotation=0)

enter image description here

Upvotes: 1

Related Questions