-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot.py
204 lines (173 loc) · 8.21 KB
/
plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import plotly.express as px
import pandas as pd
import geojson
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
def load_ds(file_path):
"""
Load the dogs of Zurich dataset from a CSV file.
Parameters:
file_path: The file path to the CSV file.
Returns:
pandas.DataFrame: A pandas DataFrame containing the data.
"""
df = pd.read_csv(file_path)
return df
def load_geojson(filename_geojson):
with open(filename_geojson) as f:
gj = geojson.load(f)
return gj
def get_dog_by_neighbourhood(df):
nb_counts = df["QuarLang"].value_counts()
df_nb = pd.DataFrame({'QuarLang': nb_counts.index, 'Count': nb_counts.values})
return df_nb
def get_dog_by_district(df):
district_counts = df["KreisLang"].value_counts()
df_district = pd.DataFrame({'KreisLang': district_counts.index, 'Count': district_counts.values})
return df_district
def get_ratio_dog_people(df_dog_by_district, df_population, nb):
if nb==True:
df_ratio = df_dog_by_district.merge(df_population, on='QuarLang')
df_ratio['ratio'] = df_ratio['Count'] / df_ratio['AnzBestWir']
return df_ratio[['QuarLang', 'ratio', 'Count', 'AnzBestWir']]
else:
df_kreis = get_kreis_data(df_population)
df_ratio = df_dog_by_district.merge(df_kreis, on='KreisLang')
df_ratio['ratio'] = df_ratio['Count_x'] / df_ratio['Count_y']
return df_ratio[['KreisLang', 'ratio', 'Count_x', 'Count_y']]
def get_kreis_data(df_population):
dict_kreis = {
"Kreis 1": ["Rathaus", "Hochschulen", "Lindenhof", "City"],
"Kreis 2": ["Wollishofen", "Leimbach", "Enge"],
"Kreis 3": ["Alt-Wiedikon", "Friesenberg", "Sihlfeld"],
"Kreis 4": ["Werd", "Langstrasse", "Hard"],
"Kreis 5": ["Gewerbeschule", "Escher Wyss"],
"Kreis 6": ["Unterstrass", "Oberstrass"],
"Kreis 7": ["Fluntern", "Hottingen", "Hirslanden", "Witikon"],
"Kreis 8": ["Seefeld", "Mühlebach", "Weinegg"],
"Kreis 9": ["Albisrieden", "Altstetten"],
"Kreis 10": ["Höngg", "Wipkingen"],
"Kreis 11": ["Affoltern", "Oerlikon", "Seebach"],
"Kreis 12": ["Saatlen", "Schwamendingen-Mitte", "Hirzenbach"]
}
# Create a new dataframe to store the population data by kreis
df_kreis = pd.DataFrame(columns=['KreisLang', 'Count'])
# Iterate over the dict_kreis and sum the population for each neighborhood in the kreis
for kreis, neighborhoods in dict_kreis.items():
kreis_population = 0
for neighborhood in neighborhoods:
# Find the row in population_df that corresponds to the neighborhood
neighborhood_df = df_population[df_population['QuarLang'] == neighborhood]
# Add the population of the neighborhood to the kreis_population
kreis_population += neighborhood_df['AnzBestWir'].sum()
# Add a row to dg_kreis with the kreis name and the sum of the population for its inner neighborhoods
df_kreis = df_kreis.append({'KreisLang': kreis, 'Count': kreis_population}, ignore_index=True)
return df_kreis
def plot():
app = dash.Dash(__name__)
# Define the layout of the app
app.layout = html.Div([
html.H1("Dog Population in Zurich", style={'color': light_gray, 'font-family': 'Merriweather','backgroundColor': dark_gray}),
# Add two buttons to switch between nb/kreis and ratio/absolute
html.Div([
dcc.RadioItems(
id='level-selector',
options=[{'label': 'Neighbourhood', 'value': 'nb'},
{'label': 'District', 'value': 'kreis'}],
value='nb',
labelStyle={'display': 'inline-block'}
),
], style={'background-color': dark_gray, 'margin': '10px', 'color': light_gray, 'font-family': 'Merriweather'}),
# Add the choropleth map figure
dcc.Graph(id='choropleth', style={'background-color': dark_gray})
], style={'background-color': dark_gray})
# Define the callback to update the choropleth map figure based on the button selections
@app.callback(
Output('choropleth', 'figure'),
Input('level-selector', 'value')
)
def update_choropleth(level):
filename_population = 'data/population.csv'
df_population = load_ds(filename_population)
color_continuous_scale = [[0, "rgb(255, 255, 255)"], [1, young_dog_rgb]]
if level == 'nb':
df_dog_by_nb = get_dog_by_neighbourhood(df)
df_ratio_dog_people = get_ratio_dog_people(df_dog_by_nb, df_population, nb=True)
fig = px.choropleth(df_ratio_dog_people,
geojson=gj,
locations='QuarLang',
color='ratio',
featureidkey="properties.name",
color_continuous_scale=color_continuous_scale,#"YlOrBr",
labels={'ratio': 'Dog to <br>human ratio'},
range_color=[0, 0.04],
custom_data=['QuarLang', 'AnzBestWir', 'Count', 'ratio']
)
fig.update_traces(hovertemplate="<br>".join([
"Neighbourhood: %{customdata[0]}",
"Population: %{customdata[1]}",
"Dogs: %{customdata[2]}",
"Dog ratio: %{customdata[3]:.3f}"
]))
if level == "kreis":
df_dog_by_district = get_dog_by_district(df)
df_ratio_dog_people = get_ratio_dog_people(df_dog_by_district, df_population, nb=False)
fig = px.choropleth(df_ratio_dog_people,
geojson=gj_kreis,
locations='KreisLang',
color='ratio',
featureidkey="properties.bezeichnung",
color_continuous_scale=color_continuous_scale,
labels={'ratio': 'Dog to <br>human ratio'},
range_color=[0, 0.04],
custom_data=['KreisLang', 'Count_y', 'Count_x', 'ratio']
)
fig.update_traces(hovertemplate="<br>".join([
"District: %{customdata[0]}",
"Population: %{customdata[1]}",
"Dogs: %{customdata[2]}",
"Dog ratio: %{customdata[3]:.3f}"
]))
fig.update_geos(fitbounds="locations",
visible=False # invisible background
)
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0},
geo=dict(center=dict(lat=47.3769, lon=8.5417), projection_scale=250000),
title_font_family="Merriweather",
title_font_size=24,
title_font_color=light_gray,
title_xanchor="center",
title_yanchor="top",
title_pad=dict(b=10),
paper_bgcolor=dark_gray,
plot_bgcolor=dark_gray,
font=dict(
family="Merriweather",
size=14,
color=light_gray
)
)
fig.update_layout(geo=dict(bgcolor='rgba(0,0,0,0)'))
fig.update_traces(marker_line_width=0.1)
return fig
app.run_server(debug=False)
if __name__ == "__main__":
male_color = "#617DFA"
female_color = "#FA6191"
total_color = "#878787"
dark_gray = '#212121'
light_gray = "#F3F3F3"
young_dog = "#F58700" # F9A743"
young_dog_rgb = "rgb(230, 99, 0)"
old_dog = "#6E6E6E" # B3B3B3"#633803"
bar_color = "#400202"
font_dict_light_gray = {"fontsize": "large", 'weight': 'light', "color": f"{light_gray}"}
filename_ds = 'data/ds.csv'
filename_geojson = 'data/zurich-city.geojson'
filename_geojson_kreis = 'data/zurich-kreis.geojson'
df = load_ds(filename_ds)
gj = load_geojson(filename_geojson)
gj_kreis = load_geojson(filename_geojson_kreis)
plot()