Search code examples
pythonmatplotlibconfusion-matrix

Plotting already calculated Confusion Matrix using Python


How can I plot in Python a Confusion Matrix similar do the one shown here for already given values of the Confusion Matrix?

In the code they use the method sklearn.metrics.plot_confusion_matrix which computes the Confusion Matrix based on the ground truth and the predictions.

But in my case, I already have calculated my Confusion Matrix. So for example, my Confusion Matrix is (values in percentages):

[[0.612, 0.388]
 [0.228, 0.772]]

Solution

  • If you check the source for sklearn.metrics.plot_confusion_matrix, you can see how the data is processed to create the plot. Then you can reuse the constructor ConfusionMatrixDisplay and plot your own confusion matrix.

    import matplotlib.pyplot as plt
    from sklearn.metrics import ConfusionMatrixDisplay
    
    cm = [0.612, 0.388, 0.228, 0.772] # your confusion matrix
    ls = [0, 1] # your y labels
    disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=ls)
    disp.plot(include_values=include_values, cmap=cmap, ax=ax, xticks_rotation=xticks_rotation)
    plt.show()