1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| pip install dash
import dash import dash_core_components as dcc import dash_html_components as html import plotly.express as px import pandas as pd
df = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"] })
app = dash.Dash(__name__)
app.layout = html.Div(children=[ html.H1(children='水果销售仪表板'), dcc.Dropdown( id='city-dropdown', options=[{'label': city, 'value': city} for city in df['City'].unique()], value='SF' ), dcc.Graph( id='example-graph' ) ])
@app.callback( dash.dependencies.Output('example-graph', 'figure'), [dash.dependencies.Input('city-dropdown', 'value')] ) def update_graph(selected_city): filtered_df = df[df['City'] == selected_city] fig = px.bar(filtered_df, x="Fruit", y="Amount", title=f"{selected_city}的水果销售") return fig
if __name__ == '__main__': app.run_server(debug=True)
|