似乎您需要的开关
Size
和
Color
.
在这种情况下,您可以利用
dcc.checklist()
在您的html中并设置样式。
这段代码很可能会工作,运行它并查看:
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"),
),
]
)
那你就不需要了
if
和
else
中的语句
update_output()
。为此,您可以拨打
update_traces()
方法
if color_on:
fig.update_traces(marker=dict(color=colormap))
if size_on:
fig.update_traces(marker=dict(size=10))
密码
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
df = px.data.iris()
color_dict = {'setosa': 'green', 'versicolor': 'yellow', 'virginica': 'red'}
colormap = df["species"].map(color_dict)
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")
if color_on:
fig.update_traces(marker=dict(color=colormap))
if size_on:
fig.update_traces(marker=dict(size=10))
return fig
if __name__ == "__main__":
app.run_server(debug=False)
笔记: