-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app.py
189 lines (155 loc) · 5.37 KB
/
streamlit_app.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
# -*- coding: utf-8 -*-
# Copyright 2018-2022 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An example of showing geographic data."""
import altair as alt
import numpy as np
import os
import pandas as pd
import pydeck as pdk
import streamlit as st
from pdb import set_trace
os.environ["STREAMLIT_BROWSER_GATHER_USAGE_STATS"] = ""
# SETTING PAGE CONFIG TO WIDE MODE AND ADDING A TITLE AND FAVICON
st.set_page_config(layout="wide", page_title="ニューヨーク市でのウーバー使用状況", page_icon=":taxi:")
# LOAD DATA ONCE
@st.cache_resource
def load_data():
data = pd.read_csv(
"uber-raw-data-sep14.csv.gz",
nrows=100000, # approx. 10% of data
names=[
"date/time",
"lat",
"lon",
], # specify names directly since they don't change
skiprows=1, # don't read header since names specified directly
usecols=[0, 1, 2], # doesn't load last column, constant value "B02512"
parse_dates=[
"date/time"
], # set as datetime instead of converting after the fact
)
return data
# FUNCTION FOR AIRPORT MAPS
def map(data, lat, lon, zoom):
st.write(
pdk.Deck(
map_style="mapbox://styles/mapbox/light-v9",
initial_view_state={
"latitude": lat,
"longitude": lon,
"zoom": zoom,
"pitch": 50,
},
layers=[
pdk.Layer(
"HexagonLayer",
data=data,
get_position=["lon", "lat"],
radius=100,
elevation_scale=4,
elevation_range=[0, 1000],
pickable=True,
extruded=True,
),
],
)
)
# FILTER DATA FOR A SPECIFIC HOUR, CACHE
@st.cache_data
def filterdata(df, hour_selected):
return df[df["date/time"].dt.hour == hour_selected]
# CALCULATE MIDPOINT FOR GIVEN SET OF DATA
@st.cache_data
def mpoint(lat, lon):
return (np.average(lat), np.average(lon))
# FILTER DATA BY HOUR
@st.cache_data
def histdata(df, hr):
filtered = data[
(df["date/time"].dt.hour >= hr) & (df["date/time"].dt.hour < (hr + 1))
]
hist = np.histogram(filtered["date/time"].dt.minute, bins=60, range=(0, 60))[0]
return pd.DataFrame({"分": range(60), "件数": hist})
# STREAMLIT APP LAYOUT
data = load_data()
# SEE IF THERE'S A QUERY PARAM IN THE URL (e.g. ?pickup_hour=2)
# THIS ALLOWS YOU TO PASS A STATEFUL URL TO SOMEONE WITH A SPECIFIC HOUR SELECTED,
# E.G. https://share.streamlit.io/streamlit/demo-uber-nyc-pickups/main?pickup_hour=2
if not st.session_state.get("url_synced", False):
try:
pickup_hour = int(st.experimental_get_query_params()["pickup_hour"][0])
st.session_state["pickup_hour"] = pickup_hour
st.session_state["url_synced"] = True
except KeyError:
pass
# IF THE SLIDER CHANGES, UPDATE THE QUERY PARAM
def update_query_params():
hour_selected = st.session_state["pickup_hour"]
st.experimental_set_query_params(pickup_hour=hour_selected)
# LAYING OUT THE TOP SECTION OF THE APP
row1_1, row1_2 = st.columns((2, 2))
with row1_1:
st.title("ニューヨーク市でのウーバー使用状況")
with row1_2:
st.write(
"""
##
0時から23時のうち、1時間の時間帯を指定してください。
"""
)
hour_selected = st.slider(
"時間帯", 0, 23, key="pickup_hour", on_change=update_query_params
)
# LAYING OUT THE MIDDLE SECTION OF THE APP WITH THE MAPS
row2_1, row2_2, row2_3, row2_4 = st.columns((2, 1, 1, 1))
# SETTING THE ZOOM LOCATIONS FOR THE AIRPORTS
la_guardia = [40.7900, -73.8700]
jfk = [40.6650, -73.7821]
newark = [40.7090, -74.1805]
zoom_level = 12
midpoint = mpoint(data["lat"], data["lon"])
with row2_1:
st.write(
f"""**{hour_selected}:00 〜 {(hour_selected + 1) % 24}:00**"""
)
map(filterdata(data, hour_selected), midpoint[0], midpoint[1], 11)
with row2_2:
st.write("**La Guardia 空港**")
map(filterdata(data, hour_selected), la_guardia[0], la_guardia[1], zoom_level)
with row2_3:
st.write("**JFK 空港**")
map(filterdata(data, hour_selected), jfk[0], jfk[1], zoom_level)
with row2_4:
st.write("**Newark 空港**")
map(filterdata(data, hour_selected), newark[0], newark[1], zoom_level)
# CALCULATING DATA FOR THE HISTOGRAM
chart_data = histdata(data, hour_selected)
# LAYING OUT THE HISTOGRAM SECTION
st.write(
f"""**毎分の使用状況:{hour_selected}:00 〜 {(hour_selected + 1) % 24}:00**"""
)
st.altair_chart(
alt.Chart(chart_data)
.mark_area(
interpolate="step-after",
)
.encode(
x=alt.X("分:Q", scale=alt.Scale(nice=False)),
y=alt.Y("件数:Q"),
tooltip=["分", "件数"],
)
.configure_mark(opacity=0.2, color="red"),
use_container_width=True,
)