代码 内有说明:
from dash import Dash, html, dcc, callback, Output, Input
import plotly. express as px
import pandas as pd
df = pd. read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv' )
app = Dash( __name__)
app. layout = html. Div( [
html. H1( children= 'Title of Dash App' , style= { 'textAlign' : 'center' } ) ,
dcc. Dropdown( options= [ { 'label' : country, 'value' : country} for country in df[ 'country' ] . unique( ) ] , value= 'Canada' , id = 'dropdown-selection' ) ,
dcc. Graph( id = 'graph-content' )
] )
@callback (
Output( 'graph-content' , 'figure' ) ,
Input( 'dropdown-selection' , 'value' )
)
def update_graph ( selected_country) :
filtered_df = df[ df[ 'country' ] == selected_country]
fig = px. line( filtered_df, x= 'year' , y= 'pop' , title= f'Population Over Time - { selected_country} ' )
return fig
if __name__ == '__main__' :
app. run( debug= True )