Is there a way to only show visible values in the legend in plotly express? So for example if this was my original scatter plot: enter image description here

and I zoom in on a few points like so: enter image description here

有没有办法只显示当前可见点的图例值,而不显示所有图例值?

代码供参考:

fig_2d = px.scatter(
    proj_2D, x=0, y=1,
    color=topic_nums.astype(str), labels={'color': 'topic'}, 
    #color_continuous_scale="spectral"
)

fig_2d.update_traces(marker=dict(size=5),
                selector=dict(mode='markers'))

fig_2d.update_layout(
    autosize=False,
    width=1000,
    height=800,
    )
fig_2d.show()

其中,Proj_2D是2D矩阵

推荐答案

您可以创建一个JupyterDash应用程序,并使用回调从zoom 事件中读取布局数据,然后相应地更新图形.要重置默认设置(图例中的所有点和轨迹),可以单击图中的Zoom Out工具提示.

import json
import numpy as np
import pandas as pd
import plotly.express as px
from jupyter_dash import JupyterDash
from dash import dcc, html, Input, Output

# Sample Data
np.random.seed(42)

proj_2D = pd.DataFrame({
    'x': np.random.uniform(low=0.0, high=1.0, size=100),
    'y': np.random.uniform(low=0.0, high=1.0, size=100),
    'topic': list(range(1,11))*10
})

proj_2D['topic'] = proj_2D['topic'].astype(str)

fig_2d = px.scatter(
    proj_2D, x='x', y='y',
    color='topic'
)

fig_2d.update_traces(marker=dict(size=5),
                selector=dict(mode='markers'))

fig_2d.update_layout(
    autosize=False,
    width=1000,
    height=800,
)

# Build App
app = JupyterDash(__name__, prevent_initial_callbacks=True)
app.layout = html.Div([
    html.H1("JupyterDash Scatter Zoom Update"),
    dcc.Graph(id='scatter-fig', figure=fig_2d),
])

@app.callback(
    Output('scatter-fig', 'figure'),
    Input('scatter-fig', 'relayoutData'),
)
def display_relayout_data(relayoutData):
    
    xaxis_min, xaxis_max = relayoutData["xaxis.range[0]"], relayoutData["xaxis.range[1]"]
    yaxis_min, yaxis_max = relayoutData["yaxis.range[0]"], relayoutData["yaxis.range[1]"]
    
    ## subset data
    proj_2D_new = proj_2D[
        proj_2D['x'].between(xaxis_min, xaxis_max) & 
        proj_2D['y'].between(yaxis_min, yaxis_max)
    ]

    fig_2d = px.scatter(
        proj_2D_new, x='x', y='y',
        color='topic'
    )
    
    fig_2d.update_traces(marker=dict(size=5),
                selector=dict(mode='markers'))

    fig_2d.update_layout(
        autosize=False,
        width=1000,
        height=800,
        )
    
    return fig_2d

# Run app and display result inline in the notebook
app.run_server(mode='inline', debug=True, port=8000)

enter image description here

Python相关问答推荐

Flask:如何在完整路由代码执行之前返回验证

我可以使用极点优化这个面向cpu的pandas代码吗?

带有pandas的分区列上的过滤器的多个条件read_parquet

Flask主机持续 bootstrap 本地IP| Python

如何知道标志是否由用户传递或具有默认值?

有什么方法可以避免使用许多if陈述

如何使用Jinja语法在HTML中重定向期间传递变量?

理解Python的二分库:澄清bisect_left的使用

难以在Manim中正确定位对象

无法通过python-jira访问jira工作日志(log)中的 comments

运行终端命令时出现问题:pip start anonymous"

如何创建一个缓冲区周围的一行与manim?

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

python中的解释会在后台调用函数吗?

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

Polars asof在下一个可用日期加入

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?

在matplotlib中使用不同大小的标记顶部添加批注

Numpyro AR(1)均值切换模型抽样不一致性

Gekko中基于时间的间隔约束