Add annotations to heatmap with slider

Hi,

I’m currently working on a project where I want to display multiple confusion matrices over several steps to check whether a ML model is drifting or not.

I’ve successfully used the figure_factory.annotated_heatmap function to create a static heatmap doing the following:

import plotly.figure_factory as ff

conf_matrix = [[1.0, 0.0, 0.0], 
                   [0.0, 1.0, 0.0], 
                   [0.5, 0.0, 0.5]]

labels = ["Negative", "Neutral", "Positive"]
labels_r = labels.copy()
labels_r.reverse()

fig = ff.create_annotated_heatmap(conf_matrix, x=labels, y=labels_r, colorscale='Blues')
fig.update_layout(
        title={
            "text": "Normalized confusion matrix",
            "xanchor": 'center',
            "yanchor": 'top',
            "y": 0.9,
            "x": 0.5,
        }
    )

fig.show()

I’ve tried to create multiple heatmaps and add a slider but it doesn’t display any of the annotations on it. Here’s how I’ve created an animated heatmap without annotations so far:

labels = ["Negative", "Neutral", "Positive"]
labels_r = labels.copy()
labels_r.reverse()

conf_matrices = []
for i in range(10):
    conf_matrices.append([[random.random(), random.random(), random.random()],
                          [random.random(), random.random(), random.random()],
                          [random.random(), random.random(), random.random()]])

animated_fig = go.Figure()

for conf_matrix in conf_matrices:
    conf_matrix.reverse()

    fig = ff.create_annotated_heatmap(conf_matrix, x=labels, y=labels_r, colorscale='Blues')

    # Adding the trace, but not the annotations
    animated_fig.add_trace(fig.data[0])
    
    # How can I also add the annotations here?


# Making the last trace visible
animated_fig.data[len(animated_fig.data)-1].visible = True

# Create and add slider
steps = []
for i in range(len(animated_fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(animated_fig.data)},
              {"title": "Normalized confusion matrix"}],
    )
    step["args"][0]["visible"][i] = True
    steps.append(step)

sliders = [dict(
    active=len(animated_fig.data)-1,
    currentvalue={"prefix": "Step: "},
    pad={"t": 50}, # Not really understanding this parameter but I'll sort it out later
    steps=steps
)]

animated_fig.update_layout(
    sliders=sliders
)

animated_fig.show()

How can I add annotations from the ff.create_annotated_heatmap figure to my graph with sliders?

Thanks!

Hi Khreas,

I’m trying to do a similar task with Confusion matrices for ML training. Were you able to figure out how to display the annotations with the slider?

Thanks!