import geopandas as gpd
from shapely import wkt
from google.oauth2 import service_account
from google.cloud import bigquery
from lets_plot import *
LetsPlot.setup_html()
def load_gdf(client, *, geometry_name, query):
df = client.query(query).result().to_dataframe()
df[geometry_name] = df[geometry_name].apply(wkt.loads)
return gpd.GeoDataFrame(df, geometry=geometry_name)
# You should add your own bigquery_credentials.json file
# See https://cloud.google.com/docs/authentication/getting-started
credentials = service_account.Credentials.from_service_account_file(
'../data/bigquery_credentials.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'],
)
client = bigquery.Client(credentials=credentials, project=credentials.project_id)
boroughs_gdf = load_gdf(client, geometry_name='borough_geom', query='''
SELECT borough_name, borough_geom
FROM `bigquery-public-data.new_york_subway.geo_nyc_borough_boundaries`
''')
stations_gdf = load_gdf(client, geometry_name='station_geom', query='''
SELECT station_name, line, station_geom
FROM `bigquery-public-data.new_york_subway.stations`
''')
lines_gdf = load_gdf(client, geometry_name='line_geom', query='''
SELECT ny_s.line, ST_MakeLine(ARRAY(
SELECT station_geom
FROM `bigquery-public-data.new_york_subway.stations`
WHERE line = ny_s.line
)) AS line_geom
FROM(
SELECT line
FROM `bigquery-public-data.new_york_subway.stations`
) AS ny_s
GROUP BY line
''')
ggplot() + \
geom_polygon(aes(fill='borough_name'), data=boroughs_gdf, color='black', alpha=.15, \
tooltips=layer_tooltips().line('@borough_name')) + \
geom_path(aes(color='line'), data=lines_gdf, size=2) + \
geom_point(data=stations_gdf, shape=1, size=1.5, color='black', \
tooltips=layer_tooltips().line('@station_name')) + \
ggtitle('NYC Subway') + \
ggsize(800, 600) + \
theme(legend_position='none', axis_title='blank', axis_text='blank', axis_ticks='blank', \
axis_line='blank', axis_tooltip='blank')