import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
df = pd.read_csv('crime_data.csv')
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].apply(lambda df: df.date().year)
df = df[df['year'] != 2022]
df['longitude'] = round(df['longitude'],3)
df['latitude'] = round(df['latitude'], 3)
scatter_df = pd.DataFrame(df.groupby(['year', 'latitude', 'longitude']).apply(lambda df: len(df)).reset_index())
scatter_df.columns = ['Year', 'Latitude', 'Longitude', 'Crime Count']
scatter_df
Year | Latitude | Longitude | Crime Count | |
---|---|---|---|---|
0 | 2016 | 41.645 | -87.615 | 2 |
1 | 2016 | 41.645 | -87.613 | 1 |
2 | 2016 | 41.645 | -87.611 | 2 |
3 | 2016 | 41.645 | -87.602 | 1 |
4 | 2016 | 41.645 | -87.574 | 1 |
... | ... | ... | ... | ... |
199775 | 2021 | 42.023 | -87.674 | 16 |
199776 | 2021 | 42.023 | -87.673 | 5 |
199777 | 2021 | 42.023 | -87.672 | 34 |
199778 | 2021 | 42.023 | -87.671 | 6 |
199779 | 2021 | 42.023 | -87.666 | 1 |
199780 rows × 4 columns
fig = px.density_mapbox(scatter_df, lat = 'Latitude', lon = 'Longitude', animation_frame = 'Year',
z = 'Crime Count', radius = 8, center = {"lat": 41.89, "lon": -87.7},
zoom = 11, width = 980, height = 600, mapbox_style = "carto-positron",
color_continuous_scale = [(0, "rgb(0, 119, 182)"), (0.5, "rgb(92, 77, 125)"), (1, "rgb(255, 0, 43)")],
range_color = [0, 70],
title = '<span style="font-weight: bold;">Chicago Yearly Crime Count Block Map</span>')
fig.update_layout(margin={"r":0,"t":80,"l":10,"b":10})
fig.update_layout(
font_family="Roboto Slab",
title_font_family="Roboto Slab",
title_font_size = 20,
paper_bgcolor="#edede9",
plot_bgcolor="#f5ebe0"
)
fig.update_layout(
hoverlabel = dict(
bgcolor = "black",
font_size = 10,
font_family = "Robot Slab"
)
)
fig['layout']['sliders'][0]['pad']=dict(t= 10, b = 30)
fig["layout"]['updatemenus'][0]['pad']=dict(r=10, t = 30)
fig.show()
fig.write_html("crime_map_block.html")