{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import geopandas as gpd\n", "from shapely import wkt\n", "\n", "from google.cloud import bigquery\n", "from google.oauth2 import service_account\n", "\n", "from lets_plot import *" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "credentials = service_account.Credentials.from_service_account_file(\n", " 'bigquery_account_credentials.json',\n", " scopes=['https://www.googleapis.com/auth/cloud-platform'],\n", ")\n", "client = bigquery.Client(credentials=credentials, project=credentials.project_id)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def load_gdf(geometry, query):\n", " df = client.query(query).result().to_dataframe()\n", " df[geometry] = df[geometry].apply(wkt.loads)\n", " return gpd.GeoDataFrame(df, geometry=geometry)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "boroughs_gdf = load_gdf('borough_geom', '''\n", " SELECT borough_name, borough_geom\n", " FROM `bigquery-public-data.new_york_subway.geo_nyc_borough_boundaries`\n", "''')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stations_gdf = load_gdf('station_geom', '''\n", " SELECT station_name, line, station_geom\n", " FROM `bigquery-public-data.new_york_subway.stations`\n", "''')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lines_gdf = load_gdf('line_geom', '''\n", " SELECT ny_s.line, ST_MakeLine(ARRAY(\n", " SELECT station_geom\n", " FROM `bigquery-public-data.new_york_subway.stations`\n", " WHERE line = ny_s.line\n", " )) AS line_geom\n", " FROM(\n", " SELECT line \n", " FROM `bigquery-public-data.new_york_subway.stations`\n", " ) AS ny_s\n", " GROUP BY line\n", "''')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ggplot() + \\\n", " geom_polygon(aes(fill='borough_name'), data=boroughs_gdf, color='black', alpha=.15) + \\\n", " scale_fill_discrete(name='') + \\\n", " geom_path(aes(color='line'), data=lines_gdf, size=2) + \\\n", " scale_color_discrete(name='Line') + \\\n", " geom_point(aes(fill='station_name'), data=stations_gdf, shape=1, size=1.5) + \\\n", " theme(axis_title='blank', axis_text='blank', axis_ticks='blank', axis_line='blank') + \\\n", " ggsize(1000, 800)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.10" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 2 }