Plotly Express一经单击即更新以筛选数据帧筛选器

2024-06-06 16:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将plotly express树地图上的单击链接到数据框上的过滤器。因此,当用户单击图表上的某个国家时,数据框将过滤特定国家,而不是显示所有国家

plotly.graph_对象有“使用单击回调更新点”,但我不确定如何使其适用于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) 

Tags: the数据indfworlddatagetnp
1条回答
网友
1楼 · 发布于 2024-06-06 16:38:06

这里有一些技巧:

  • 将plotly express的输出转换为具有datalayout属性的FigureWidget。这使我们能够添加回调
  • 使用带有display_id的显示句柄dh来更新显示的数据帧
  • 使用display(fig)而不是fig.show()来调用小部件上的回调

为了便于检查,我还将filtered_df标记为全局,但如果您只想显示它,则不需要这样做

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)

参考:

相关问题 更多 >