Untitled
unknown
plain_text
9 months ago
3.2 kB
6
Indexable
import plotly.express as px # Define colors for above and below average groups color_map = { 'above': 'green', # Color for above average countries 'below': 'red' # Color for below or equal to average countries } # Create a column to categorize countries based on whether they are above or below the global average population_65_above['Category'] = population_65_above['Value'].apply(lambda x: 'above' if x > global_average else 'below') # Filter data for above average and below average above_average_data = population_65_above[population_65_above['Category'] == 'above'] below_average_data = population_65_above[population_65_above['Category'] == 'below'] # Create a choropleth map for countries above the global average fig = px.choropleth( above_average_data, # Data source locations='CountryCode', # Column specifying the countries (ISO country codes) color='Category', # Categorized by 'above' color_discrete_map={'above': 'green'}, # Use green for above average hover_name='CountryName', # Column to display country names on hover title='Countries with Population Ages 65+ Above Average', # Title of the plot labels={'Category': 'Population 65+'}, # Label for the color bar projection='natural earth' # Map projection type ) # Add a second trace for countries below the global average fig.add_trace(px.choropleth( below_average_data, # Data source for below-average countries locations='CountryCode', # Country codes color='Category', # Coloring by 'below' color_discrete_map={'below': 'red'}, # Use red for below average hover_name='CountryName', # Display country names on hover title='Countries with Population Ages 65+ Below Average', # Title for this layer labels={'Category': 'Population 65+'}, # Label for the color bar projection='natural earth' # Use the same map projection ).data[0]) # Extract the first trace (choropleth trace) from the plot # Add a dropdown menu to switch between different map views (above average, below average) fig.update_layout( updatemenus=[{ 'buttons': [ { 'method': 'update', # Method to update the visibility of traces 'label': 'Above Average', # Label for the first button 'args': [ {'visible': [True, False]}, # Show only the first trace (above-average countries) {'title': 'Countries with Population Ages 65+ Above Average'} # Update the plot title ] }, { 'method': 'update', # Method to update the visibility of traces 'label': 'Below Average', # Label for the second button 'args': [ {'visible': [False, True]}, # Show only the second trace (below-average countries) {'title': 'Countries with Population Ages 65+ Below Average'} # Update the plot title ] } ], 'direction': 'down', # Dropdown menu direction 'showactive': True # Show the currently active option in the dropdown }] ) # Display the final interactive plot fig.show()
Editor is loading...
Leave a Comment