我有一个 Plotty DataTable,显示 Pandas DataFrame。 DataFrame 中的每一列都有一个折线图。每个折线图对于数据中表示的每个 ID 都有一条线。我试图让将奇怪的图形数据与原始输入数据关联起来变得更容易。
我希望能够单击一个数据点(或者更好的是在 ChartLegend 中选择一行),这样做会导致 DataTable 进行过滤并仅显示与所选 ID 关联的行。
这是我如何生成数据表和图表的代码片段
def Make_PlottyFigures(df, xcol_name, device_type_dict, device_names, columns_to_plot):
figs = []
for col_i in range(0, len(columns_to_plot)):
figs.append(go.Figure())
#Go over each device, and add a trace for each column to the appropriate figure. We want each colun in its own figure
for device in device_names:
if df[df['id'] == device].shape[0] > 0:
axs_index = 0
for col in columns_to_plot:
figs[axs_index].add_trace(go.Scatter(x=df[xcol_name], y=df[df['id'] == device][col],
mode='lines+markers',
name=f"{device_type_dict[device]}-{device}"))
axs_index += 1
index = 0;
for col in columns_to_plot:
figs[index].update_layout(
title=f"{col}",
xaxis_title="",
yaxis_title="",
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
index += 1
return figs
def DASH_dataTable_from_pd(id, df):
return dash_table.DataTable(
id=f'datatable-{id}',
columns=[
{"name": i, "id": i, "deletable": False, "selectable": False} for i in df.columns
],
data=df.to_dict('records'),
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_selectable="multi",
row_deletable=False,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current= 0,
page_size= 10,
)
我尝试在网上寻找类似的东西,但没有找到任何东西。 https://dash.plotly.com/datatable/interactivity有一个“排序”示例,但方向相反(在表中进行选择突出显示等效的图表数据条目)。 https://dash-docs.herokuapp.com/interactive-graphing有关于如何对我感兴趣的事件使用react的示例,我只是专注于如何让表过滤掉这些事件触发(也使其可发布会很好)
是否有我错过的任何示例,或者这是非常明显的,我遗漏了一些东西
最佳答案
最简单的方法是重新设置表的 data
属性,仅传递要显示的行。您可以监听跟踪单击事件,通过索引、customdata 或 clickData 对象附带的任何其他属性确定单击的跟踪。
这个基本示例说明了这个想法:
df = [...]
@app.callback(
Output("my-table", "data"),
[Input("my-plot", "clickData")]
)
def on_trace_click(click_data):
"""Listen to click events and update table, passing filtered rows"""
p = trace_click['points'][0]
# here, use 'customdata' property of clicked point,
# could also use 'curveNumber', 'pointIndex', etc.
if 'customdata' in p:
key = p['customdata']['my-key']
df_f = get_corresponding_rows(df, key)
return df_f.to_dict('records')
def get_corresponding_rows(df, my_key):
"""Filter df, return rows that match my_key"""
return df[df['key-column'] == my_key]
重要的是,您的行 ID 不会仅仅因为过滤而发生更改。这样,任何样式、选定状态等仍将正确应用。
关于python - 阴谋冲刺 : filter DataTable based on plot selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61651645/