vgosavi2 commited on
Commit
9f7e69b
·
verified ·
1 Parent(s): 3397ec7

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +37 -26
src/streamlit_app.py CHANGED
@@ -88,35 +88,46 @@ chart1 = (
88
  )
89
  st.altair_chart(chart1, use_container_width=True)
90
 
91
- # Base pie chart (innerRadius=50 gives us the donut)
92
- base = (
93
- alt.Chart(top_crimes)
94
- .mark_arc(innerRadius=50)
95
- .encode(
96
- theta=alt.Theta("Count:Q"),
97
- color=alt.Color("Crime Type:N", legend=alt.Legend(title="Crime Type")),
98
- tooltip=[
99
- alt.Tooltip("Crime Type:N"),
100
- alt.Tooltip("Count:Q"),
101
- alt.Tooltip("Percentage:Q", format=".1%")
102
- ]
103
- )
 
104
  )
 
 
105
 
106
- # Add labels *outside* each slice by using a larger radius
107
- labels = (
108
- alt.Chart(top_crimes)
109
- .mark_text(radius=120, size=11, fontWeight="bold")
110
- .encode(
111
- theta=alt.Theta("Count:Q"),
112
- text=alt.Text("Crime Type:N")
113
- )
 
 
 
 
 
 
 
114
  )
115
 
116
- # Combine and set size/title
117
- chart2 = (
118
- (base + labels)
119
- .properties(width=600, height=600, title="Top 10 Crime Types")
120
  )
121
 
122
- st.altair_chart(chart2, use_container_width=False)
 
 
88
  )
89
  st.altair_chart(chart1, use_container_width=True)
90
 
91
+ ###############################################################
92
+
93
+ import plotly.express as px
94
+
95
+ # 4. Pie Chart 1: Top 10 Crime Types
96
+ st.header("Pie Chart 1: Top 10 Crime Types Distribution")
97
+
98
+ # Prepare Top 10 crime types
99
+ top_crimes = (
100
+ df["crm_cd_desc"]
101
+ .value_counts()
102
+ .nlargest(10)
103
+ .rename_axis("Crime Type")
104
+ .reset_index(name="Count")
105
  )
106
+ # Compute percentages
107
+ top_crimes["Percentage"] = top_crimes["Count"] / top_crimes["Count"].sum()
108
 
109
+ # Build Plotly pie chart
110
+ fig = px.pie(
111
+ top_crimes,
112
+ names="Crime Type",
113
+ values="Count",
114
+ hole=0.4, # makes it a donut
115
+ hover_data=["Percentage"], # show percentage on hover
116
+ title="Top 10 Crime Types"
117
+ )
118
+
119
+ # Move labels outside slices and show both label & percent
120
+ fig.update_traces(
121
+ textposition="outside",
122
+ textinfo="label+percent",
123
+ marker=dict(line=dict(color="#000000", width=1)) # add slice borders
124
  )
125
 
126
+ # Style the legend
127
+ fig.update_layout(
128
+ legend_title_text="Crime Type",
129
+ margin=dict(t=50, l=25, r=25, b=25)
130
  )
131
 
132
+ # Render in Streamlit
133
+ st.plotly_chart(fig, use_container_width=True)