Figure factory heatmap in Plotly with buttons

Viewed 456

I have two dataframes that I want to fit in an annotated heat map, and I want the user to be able to toggle between the two heat maps with buttons.

Problem is I can’t get update_layout to work as I expect it to. Here is my script:

a = np.random.rand(5, 5)
b = np.random.rand(5, 5)

fig = ff.create_annotated_heatmap()

a = [dict(a, 
        annotation_text=a,
           )]
b = [dict(b, 
        annotation_text=b,
           )]

fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            buttons=list([
                dict(label="choose a",
                     method="update",
                     args=[{"visible": [True, False]},
                           {"title": "a is best",
                           }]),
                dict(label="choose b",
                     method="update",
                     args=[{"visible": [False, True]},
                           {"title": "b is better",
                           }]),
            ]),
        )
    ])

fig.show()

This returns:

TypeError: create_annotated_heatmap() missing 1 required positional argument: 'z'

What am I missing here?

1 Answers

You're getting this error because the z argument is missing. Use this to make a figure factory annotated heatmap:

a = np.random.randint(10, size=(2, 4))
fig = ff.create_annotated_heatmap(z=a, colorscale='Viridis')

To add other values using buttons, take a look at the snippet below that produces this plot for the options z=a and z=b:

Plot 1: z=a

enter image description here

Plot 2: z=b

enter image description here

Complete code:

import plotly.figure_factory as ff
import numpy as np

np.random.seed(123)
a = np.random.randint(10, size=(2, 4))
b = np.random.randint(10, size=(2, 4))

fig = ff.create_annotated_heatmap(z=a, colorscale='Viridis')

# Add dropdown
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=[{'z':[a]}],
                    label="Select a",
                    method="update"
                ),
                dict(
                    args=[{'z':[b]}],
                    label="Select b",
                    method="update"
                )
            ]),
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=-0.2,
            xanchor="left",
            y=0.8,
            yanchor="top"
        ),
    ]
)

fig.show()
Related