使用 Plotly 的突出显示功能控制图例行为

问题描述 投票:0回答:1

当前代码是当我们选择图例时数据点消失。我想要的恰恰相反。我想要的是相反的,突出显示,标记数据点。

我检查过 使用 Plotly 的突出显示功能和 ggplotly 控制图例行为Plotly - 反转图例单击选择?

尝试转换成python

import plotly.graph_objects as go
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px

# Load the iris dataset from plotly
iris = px.data.iris()

app = dash.Dash(__name__)

# Initial scatter plot
fig = go.Figure()

for s in iris['species'].unique():
    subset = iris[iris['species'] == s]
    fig.add_trace(go.Scatter(
        x=subset['petal_length'],
        y=subset['petal_width'],
        mode='markers',
        name=s
    ))

app.layout = html.Div([
    dcc.Graph(id='iris-plot', figure=fig),
])

@app.callback(
    Output('iris-plot', 'figure'),
    Input('iris-plot', 'clickData')
)
def toggle_opacity(clickData):
    # If a legend item is clicked
    if clickData and 'curveNumber' in clickData['points'][0]:
        curveNumber = clickData['points'][0]['curveNumber']
        current_opacity = fig.data[curveNumber].marker.opacity
        new_opacity = 0.3 if current_opacity == 1 else 1
        fig.data[curveNumber].marker.opacity = new_opacity
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)
python plot plotly plotly-dash
1个回答
0
投票

有这样的事吗?这是使用您当前代码的算法逻辑,只是简单地将不透明度交换为绘图数据的不同属性。

import dash
from dash import dcc, html
from dash.dependencies import Input, Output

import plotly.express as px
import plotly.graph_objects as go

iris = px.data.iris()

app = dash.Dash(__name__)

fig = go.Figure()

for s in iris["species"].unique():
    subset = iris[iris["species"] == s]
    fig.add_trace(
        go.Scatter(
            x=subset["petal_length"],
            y=subset["petal_width"],
            mode="markers",
            name=s,
            marker=dict(size=6),
        )
    )

app.layout = html.Div([dcc.Graph(id="iris-plot", figure=fig)])


@app.callback(Output("iris-plot", "figure"), Input("iris-plot", "clickData"))
def toggle_marker_size(clickData):
    if clickData and "curveNumber" in clickData["points"][0]:
        curveNumber = clickData["points"][0]["curveNumber"]
        current_size = fig.data[curveNumber].marker.size
        new_size = 12 if current_size == 6 else 6
        fig.data[curveNumber].marker.size = new_size
    return fig


if __name__ == "__main__":
    app.run_server(debug=True)

给出:

© www.soinside.com 2019 - 2024. All rights reserved.