单图上的双图切换 - python

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

我有两个独立的切换开关,可以在散点图上启动颜色和大小。这些独立工作得很好,但我希望将它们组合起来,这样当两个开关都打开时,颜色和尺寸都会更新。

我无法调用单个散点图,然后使用

update_trace
,因为我需要为
species
列分配离散值。

我不知道颜色和尺寸是否可以更新为现有的图形,但我愿意改变。

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go

df = px.data.iris()
color_dict = {'versicolor': 'brown', 'setosa': 'orange', 'virginica': 'pink'}
size_dict = {'versicolor': 4, 'setosa': 6, 'virginica': 10}

sizemap = df["species"].map(size_dict)

df = df.sort_values(by = 'species', ascending= False).reset_index(drop = True)

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.P("Toggle for the Color"),
        dcc.Checklist(
            id="color_toggle",
            options=[{"label": "", "value": True}],
            value=[],
            inline=True
        ),
        html.P("Toggle for the Size"),
        dcc.Checklist(
            id="size_toggle",
            options=[{"label": "", "value": True}],
            value=[],
            inline=True
        ),
        html.Div(
            dcc.Graph(id="chart"),
        ),
    ]
)


@app.callback(
    Output("chart", "figure"),
    [Input("color_toggle", "value"), 
     Input("size_toggle", "value")]
)
def update_output(color_on, size_on):
    fig = px.scatter(df, x="sepal_width", y="sepal_length", hover_data=["species"])

    if color_on:
        fig = px.scatter(df, x="sepal_width", y="sepal_length", color = "species", color_discrete_map = color_dict)

    if size_on:
        fig = go.Figure(data=go.Scatter(
                    x=df["sepal_width"], 
                    y=df["sepal_length"],
                    mode = 'markers', 
                    marker=dict(size=sizemap)
                    ))
    
    # return both color and szie
    #if color_on & size_on:

    return fig


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

注意,您还可以直接使用

size
 设置标记 
px.scatter()
,参考特定列,如
color
:

# nb. `sizemap` would be invalid because you are sorting the df *after* this line
#sizemap = df["species"].map(size_dict)

# Create a column instead
df["size"] = df["species"].map(size_dict)

还有回调:

@app.callback(
    Output("chart", "figure"),
    [Input("color_toggle", "value"),
     Input("size_toggle", "value")]
)
def update_output(color_on, size_on):

    fig = px.scatter(
        df,
        x="sepal_width",
        y="sepal_length",
        color="species" if color_on else None,
        size="size" if size_on else None,
        color_discrete_map=color_dict,
        hover_data={"species": True, "size": False}
    )

    fig.update_traces(marker_sizemode='diameter', marker_sizeref=1)

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