1

I am trying to link a click on the plotly express tree map to a filter on the data frame. So when a user clicks on a country on the graph, the dataframe will filter for the specific country instead of showing all

There is "Update points using a click callback" for plotly.graph_objects but I am not sure how to make it work for plotly express.

import numpy as np
df = px.data.gapminder().query("year == 2007")
df["world"] = "world" # in order to have a single root node
fig = px.treemap(df, path=['world', 'continent', 'country'], values='pop',
               color='lifeExp', hover_data=['iso_alpha'],
               color_continuous_scale='RdBu',
               color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()
## when user clicks on a country in the tree-map, the get_data function filters the df and outputs specific data on the country 

def get_data(df, click):
    return df[df['country'] == click]

get_data(df,click) 

1 Answer 1

5

There are a few tricks:

  • Convert the output of plotly express to a FigureWidget with data and layout attributes. This enables us to add a callback.
  • Use a display handle dh with a display_id to update the showed dataframe.
  • Use display(fig) instead of fig.show(), in order to invoke the callbacks on the widget.

I also marked filtered_df as global in order to have it available for inspection, but if you just want to display it that is not necessary.

import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from IPython.display import display

df = px.data.gapminder().query("year == 2007")
df["world"] = "world"  # in order to have a single root node


def filter_country(trace, points, state):
    global filtered_df
    region = trace.labels[points.point_inds[0]]
    filtered_df = df[(df["country"] == region) | (df["continent"] == region)]

    dh.update(filtered_df)


fig = px.treemap(
    df,
    path=["world", "continent", "country"],
    values="pop",
    color="lifeExp",
    hover_data=["iso_alpha"],
    color_continuous_scale="RdBu",
    color_continuous_midpoint=np.average(df["lifeExp"], weights=df["pop"]),
)

fig = go.FigureWidget(fig.data, fig.layout)

fig.data[0].on_click(filter_country)

display(fig)
dh = display(display_id=True)

Reference:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.