Plotly: How to make an annotated confusion matrix using a heatmap?

Written by- Aionlinecourse1726 times views

Image
To create an annotated confusion matrix using a heatmap in Plotly, you will need to use the go.Heatmap trace type. Here is an example of how you can do this:
import plotly.express as px
import plotly.graph_objects as go

# Define the confusion matrix and labels
confusion_matrix = [[10, 2, 3], [4, 5, 6], [7, 8, 9]]
labels = ['Class 1', 'Class 2', 'Class 3']

# Create the heatmap trace
heatmap = go.Heatmap(z=confusion_matrix, x=labels, y=labels, colorscale='Viridis')

# Create the figure and add the heatmap trace
fig = go.Figure(data=[heatmap])

# Add annotations for each cell in the confusion matrix
for i in range(len(confusion_matrix)):
    for j in range(len(confusion_matrix[i])):
        fig.add_annotation(
            text=confusion_matrix[i][j],
            x=labels[j],
            y=labels[i],
            xref='x',
            yref='y'
        )

# Show the figure
fig.show()
This will create a heatmap of the confusion matrix, with each cell in the matrix annotated with its value. You can customize the appearance of the heatmap and the annotations by using the various options available in the go.Heatmap and fig.add_annotation functions.