Skip to content

Instantly share code, notes, and snippets.

@hirosh
Last active March 7, 2023 00:40
Show Gist options
  • Save hirosh/f0fe6fc17ea396fb49a0e8b5c392a16d to your computer and use it in GitHub Desktop.
Save hirosh/f0fe6fc17ea396fb49a0e8b5c392a16d to your computer and use it in GitHub Desktop.
plotly.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOfsoUxQhDnvyJOadVGMP56",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/hirosh/f0fe6fc17ea396fb49a0e8b5c392a16d/plotly.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"source": [
"!pip install geocoder"
],
"metadata": {
"id": "RcX3zSo3fRi1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# 奈良県の令和四年度行政区域データ(国土交通省)\n",
"!wget https://nlftp.mlit.go.jp/ksj/gml/data/N03/N03-2022/N03-20220101_29_GML.zip\n",
"!unzip N03-20220101_29_GML.zip"
],
"metadata": {
"id": "iVuINNDpgo_f"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#総務省 奈良県の市区町村別の人口及び世帯数\n",
"!wget https://www.soumu.go.jp/main_content/000033865.xls"
],
"metadata": {
"id": "aIGCX47nhQ82"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import json\n",
"import re\n",
"import pandas as pd\n",
"import plotly.express as px\n",
"import geocoder as geocoder\n",
"\n",
"# 定数\n",
"PREFECTURE = \"奈良県\"\n",
"XLS_FILE = \"/content/000033865.xls\"\n",
"GEOJSON_FILE = \"/content/N03-22_29_220101.geojson\"\n",
"MAPBOX_STYLE = \"carto-positron\"\n",
"COLOR_RANGE = (0, 360000)\n",
"ZOOM_LEVEL = 8\n",
"OPACITY = 0.5\n",
"FIG_SIZE = 800\n",
"\n",
"\n",
"def load_data(XLS_FILE, geojson_file):\n",
" \"\"\"XLSファイルとGeoJSONファイルからデータフレームとGeoJSONを作成する\"\"\"\n",
" # XLSファイルから人口データフレーム作成\n",
" df = pd.read_excel (r\"/content/000033865.xls\", header=1)\n",
" # 市町村名から重複などを取り除く\n",
" df[\"団体名\"] = df[\"団体名\"].replace(re.compile(r\"(.+?郡)(.+?[町村])\"), r\"\\2\", regex=True)\n",
" df=df[~df[\"団体名\"].str.endswith('郡', na=False)]\n",
" df=df[~df[\"団体名\"].str.endswith('県', na=False)]\n",
"\n",
" # コラム名を変更し、数値型に変換する\n",
" df.columns = ['市区町村名', '男', '女', '計', '世帯数']\n",
" df[['男', '女', '計', '世帯数']] = df[['男', '女', '計', '世帯数']].replace(',', '', regex=True).astype('float')\n",
"\n",
" # GeoJSONファイルから地図データ読み込み\n",
" with open(geojson_file) as f:\n",
" geojson = json.load(f)\n",
" # GeoJSONデータから不要な列を削除する\n",
" for feature in geojson['features']:\n",
" feature['properties'].pop('N03_001')\n",
" feature['properties'].pop('N03_002')\n",
" feature['properties'].pop('N03_003')\n",
" feature['properties'].pop('N03_007')\n",
"\n",
" return df, geojson\n",
"\n",
"def plot_map(df, geojson, prefecture):\n",
" \"\"\"データフレームとGeoJSONから地図をプロットする\"\"\"\n",
" # 都道府県の中心座標を取得\n",
" center_latlng = geocoder.arcgis(prefecture).latlng\n",
"\n",
" # コロプレスマップを描画\n",
" fig = px.choropleth_mapbox(\n",
" df,\n",
" geojson=geojson,\n",
" locations=\"市区町村名\",\n",
" color=\"計\",\n",
" hover_name=\"市区町村名\",\n",
" hover_data=[\"男\", \"女\", \"世帯数\"],\n",
" featureidkey=\"properties.N03_004\",\n",
" mapbox_style=MAPBOX_STYLE,\n",
" range_color=COLOR_RANGE,\n",
" zoom=ZOOM_LEVEL,\n",
" center={\"lat\": center_latlng[0]-0.5, \"lon\": center_latlng[1]},\n",
" opacity=OPACITY,\n",
" width=FIG_SIZE,\n",
" height=FIG_SIZE,\n",
" )\n",
" fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))\n",
" fig.show()\n",
"\n",
"# メイン処理\n",
"if __name__ == \"__main__\":\n",
" df_nara, geojson_nara = load_data(XLS_FILE, GEOJSON_FILE)\n",
" plot_map(df_nara, geojson_nara, PREFECTURE)"
],
"metadata": {
"id": "IO8UUX6GfXmO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Geojsonのファイルの市区町村名を確認する\n",
"for i in range(len(geojson_nara[\"features\"])):\n",
" print(geojson_nara[\"features\"][i][\"properties\"])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "d5KQEUo_v1I7",
"outputId": "2baa0491-eb20-4527-8e09-b701d9081ae3"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"41\n",
"{'N03_004': None}\n",
"{'N03_004': '奈良市'}\n",
"{'N03_004': '大和高田市'}\n",
"{'N03_004': '大和郡山市'}\n",
"{'N03_004': '天理市'}\n",
"{'N03_004': '橿原市'}\n",
"{'N03_004': '桜井市'}\n",
"{'N03_004': '五條市'}\n",
"{'N03_004': '御所市'}\n",
"{'N03_004': '生駒市'}\n",
"{'N03_004': '香芝市'}\n",
"{'N03_004': '葛城市'}\n",
"{'N03_004': '宇陀市'}\n",
"{'N03_004': '山添村'}\n",
"{'N03_004': '平群町'}\n",
"{'N03_004': '三郷町'}\n",
"{'N03_004': '斑鳩町'}\n",
"{'N03_004': '安堵町'}\n",
"{'N03_004': '川西町'}\n",
"{'N03_004': '三宅町'}\n",
"{'N03_004': '田原本町'}\n",
"{'N03_004': '曽爾村'}\n",
"{'N03_004': '御杖村'}\n",
"{'N03_004': '高取町'}\n",
"{'N03_004': '明日香村'}\n",
"{'N03_004': '上牧町'}\n",
"{'N03_004': '王寺町'}\n",
"{'N03_004': '広陵町'}\n",
"{'N03_004': '河合町'}\n",
"{'N03_004': '河合町'}\n",
"{'N03_004': '吉野町'}\n",
"{'N03_004': '大淀町'}\n",
"{'N03_004': '下市町'}\n",
"{'N03_004': '黒滝村'}\n",
"{'N03_004': '天川村'}\n",
"{'N03_004': '野迫川村'}\n",
"{'N03_004': '十津川村'}\n",
"{'N03_004': '下北山村'}\n",
"{'N03_004': '上北山村'}\n",
"{'N03_004': '川上村'}\n",
"{'N03_004': '東吉野村'}\n"
]
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "aDzeyLDxwq0e"
},
"execution_count": 5,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment