hyzhang00 commited on
Commit
460f49c
·
verified ·
1 Parent(s): 306f014

Update: change plotly event to plotly chart

Browse files
Files changed (1) hide show
  1. app.py +46 -56
app.py CHANGED
@@ -81,9 +81,8 @@ def create_severity_violation_chart(df, age_group=None):
81
  color='Severity',
82
  title=f'Crash Severity Distribution by Violation Type - {age_group}',
83
  labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'},
84
- color_discrete_map=severity_colors,
85
- width=800,
86
-
87
  )
88
 
89
  # fig.update_layout(
@@ -95,24 +94,12 @@ def create_severity_violation_chart(df, age_group=None):
95
  # modified the above code because x-axis labels were partially pruned
96
  fig.update_layout(
97
  xaxis_tickangle=-45,
98
- legend=dict(
99
- orientation='v',
100
- x=1,
101
- y=1,
102
- yanchor='top',
103
- xanchor='left',
104
- title="Severity Level"
105
- ),
106
  barmode='stack',
107
- margin=dict(t=50, b=250,r=20), # Increase bottom margin to avoid pruning
108
- xaxis=dict(
109
- tickangle=-45,
110
- tickfont=dict(size=9),
111
- dtick=1,)
112
  )
113
 
114
-
115
-
116
  # return fig
117
  return fig, violations
118
 
@@ -186,7 +173,7 @@ def create_map_bar_chart(df, selected_year):
186
  fig.update_layout(
187
  clickmode='event+select', # Enable interactivity
188
  xaxis_tickangle=45, # Rotate x-axis labels 45 degrees
189
- margin=dict(t=50, b=150, r=20), # Add bottom margin to prevent label cutoff
190
  )
191
  return fig
192
 
@@ -514,77 +501,80 @@ def main():
514
  """)
515
 
516
  with tab2:
517
- # Age group selection
518
  age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+']
519
  selected_age = st.selectbox('Select Age Group:', age_groups)
 
 
520
 
521
- chart_col, desc_col = st.columns([7, 4])
522
-
523
- with chart_col:
524
- # Create and display chart
525
  fig, violations = create_severity_violation_chart(df, selected_age)
 
 
 
 
 
 
 
 
526
 
527
- clicked_points = plotly_events(fig, click_event=True, override_height=600, override_width="100%")
528
-
529
- if clicked_points:
530
- selected_violation = clicked_points[0]['x']
531
- if selected_violation != st.session_state['selected_violation']:
532
- st.session_state['selected_violation'] = selected_violation
533
-
534
- # If a violation is selected, display the pie chart --> added for part3 (interactive pie chart)
535
- if st.session_state['selected_violation']:
536
- # pie_chart = create_interactive_pie_chart(violations, st.session_state['selected_violation'])
537
- pie_chart = create_interactive_pie_chart(violations, st.session_state['selected_violation'], selected_age) # dynamically update pie chart's title
538
  st.plotly_chart(pie_chart, use_container_width=True)
539
 
540
- # Display statistics
541
- if selected_age == 'All Ages':
542
- total_incidents = len(df)
543
- else:
544
- total_incidents = len(df[
545
- (df['Age_Group_Drv1'] == selected_age) |
546
- (df['Age_Group_Drv2'] == selected_age)
547
- ])
 
 
548
 
549
-
550
- with desc_col:
551
  st.markdown("""
552
  # Severity of Violations Across Age Groups
553
-
554
  This section provides an interactive visualization of **crash severities** linked to specific violation types, segmented by driver age groups. It enables a comprehensive analysis of how **age influences crash severity and violation trends**. The visualization is linked to an **interactive pie chart** that updates when a specific bar is selected, displaying the detailed distribution of the selected violation type based on the selected age group.
555
-
556
  ---
557
-
558
  ## **Key Features**
559
-
560
  ### 1. **Age Group Analysis**
561
  - Select specific age groups (e.g., "16-25", "65+") or analyze all ages to explore correlations between:
562
  - Age
563
  - Violation type
564
  - Crash severity
565
  - Understand how different age groups are involved in various types of violations.
566
-
567
  ### 2. **Violation Breakdown**
568
  - Examine the most frequent violations contributing to traffic accidents for each age group.
569
  - View detailed statistics showing the distribution of violation types.
570
-
571
  ### 3. **Understanding Severity Level**
572
  - Identify the proportion of severity levels for a specific violation type based on different age groups.
573
  - Investigate detailed severity patterns for each violation type across age groups.
574
-
575
  ---
576
-
577
  ## **Insights**
578
-
579
  - **Identifies High-Risk Behaviors:**
580
  - Highlights risky behaviors such as reckless driving in younger drivers or impaired driving in older groups.
581
 
582
  - **Highlights Severity Associations:**
583
  - Shows which violations are associated with more severe outcomes, aiding targeted safety interventions and public awareness campaigns.
584
-
585
  - **Supports Data-Driven Decision Making:**
586
  - Provides insights for designing **age-specific traffic safety programs**.
587
-
588
  ---
589
  """)
590
 
 
81
  color='Severity',
82
  title=f'Crash Severity Distribution by Violation Type - {age_group}',
83
  labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'},
84
+ height=600,
85
+ color_discrete_map=severity_colors, # --> for part 3
 
86
  )
87
 
88
  # fig.update_layout(
 
94
  # modified the above code because x-axis labels were partially pruned
95
  fig.update_layout(
96
  xaxis_tickangle=-45,
97
+ legend_title='Severity Level',
 
 
 
 
 
 
 
98
  barmode='stack',
99
+ margin=dict(t=50, b=150), # Increase bottom margin to avoid pruning
100
+ xaxis=dict(automargin=True)
 
 
 
101
  )
102
 
 
 
103
  # return fig
104
  return fig, violations
105
 
 
173
  fig.update_layout(
174
  clickmode='event+select', # Enable interactivity
175
  xaxis_tickangle=45, # Rotate x-axis labels 45 degrees
176
+ margin=dict(t=50, b=150), # Add bottom margin to prevent label cutoff
177
  )
178
  return fig
179
 
 
501
  """)
502
 
503
  with tab2:
504
+
505
  age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+']
506
  selected_age = st.selectbox('Select Age Group:', age_groups)
507
+
508
+ trend_col, desc_col = st.columns([6, 4])
509
 
510
+ with trend_col:
511
+ # Create and display main chart
 
 
512
  fig, violations = create_severity_violation_chart(df, selected_age)
513
+
514
+ # Display the chart with selection events enabled
515
+ chart_event = st.plotly_chart(
516
+ fig,
517
+ use_container_width=True,
518
+ key="violation_chart",
519
+ on_select="rerun"
520
+ )
521
 
522
+ # Check if there's a selection event
523
+ if chart_event and chart_event.selection and chart_event.selection.points:
524
+ # Get the selected violation type
525
+ selected_violation = chart_event.selection.points[0]['x']
526
+ # Create and display pie chart for selected violation
527
+ pie_chart = create_interactive_pie_chart(violations, selected_violation, selected_age)
 
 
 
 
 
528
  st.plotly_chart(pie_chart, use_container_width=True)
529
 
530
+ # # Display statistics
531
+ # if selected_age == 'All Ages':
532
+ # total_incidents = len(df)
533
+ # else:
534
+ # total_incidents = len(df[
535
+ # (df['Age_Group_Drv1'] == selected_age) |
536
+ # (df['Age_Group_Drv2'] == selected_age)
537
+ # ])
538
+
539
+ with desc_col:
540
 
 
 
541
  st.markdown("""
542
  # Severity of Violations Across Age Groups
543
+
544
  This section provides an interactive visualization of **crash severities** linked to specific violation types, segmented by driver age groups. It enables a comprehensive analysis of how **age influences crash severity and violation trends**. The visualization is linked to an **interactive pie chart** that updates when a specific bar is selected, displaying the detailed distribution of the selected violation type based on the selected age group.
545
+
546
  ---
547
+
548
  ## **Key Features**
549
+
550
  ### 1. **Age Group Analysis**
551
  - Select specific age groups (e.g., "16-25", "65+") or analyze all ages to explore correlations between:
552
  - Age
553
  - Violation type
554
  - Crash severity
555
  - Understand how different age groups are involved in various types of violations.
556
+
557
  ### 2. **Violation Breakdown**
558
  - Examine the most frequent violations contributing to traffic accidents for each age group.
559
  - View detailed statistics showing the distribution of violation types.
560
+
561
  ### 3. **Understanding Severity Level**
562
  - Identify the proportion of severity levels for a specific violation type based on different age groups.
563
  - Investigate detailed severity patterns for each violation type across age groups.
564
+
565
  ---
566
+
567
  ## **Insights**
568
+
569
  - **Identifies High-Risk Behaviors:**
570
  - Highlights risky behaviors such as reckless driving in younger drivers or impaired driving in older groups.
571
 
572
  - **Highlights Severity Associations:**
573
  - Shows which violations are associated with more severe outcomes, aiding targeted safety interventions and public awareness campaigns.
574
+
575
  - **Supports Data-Driven Decision Making:**
576
  - Provides insights for designing **age-specific traffic safety programs**.
577
+
578
  ---
579
  """)
580