Last active
March 2, 2025 06:25
-
-
Save ksasao/1f8160e0b9d101d6d5480749e1161a46 to your computer and use it in GitHub Desktop.
シンプルな日本地図上にマーカーをプロットします https://x.com/ksasao/status/1896076372617150879
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import cartopy.crs as ccrs | |
import cartopy.feature as cfeature | |
import pandas as pd | |
from PIL import Image | |
import numpy as np | |
import os | |
# CSVファイルを読み込む | |
# https://github.com/ksasao/ekimemo/blob/main/src/20250304/data.csv をローカルに保存してください | |
df = pd.read_csv('data.csv', encoding='utf-8', header=None, names=['name', 'name_kana', 'lat', 'lon', 'radius']) | |
# 指定した緯度経度の範囲 | |
#lat_min, lat_max = df['lat'].min() - 1, df['lat'].max() + 1 | |
#lon_min, lon_max = df['lon'].min() - 4, df['lon'].max() + 4 | |
lat_min, lat_max = df['lat'].min() - 6, df['lat'].max() + 6 | |
lon_min, lon_max = df['lon'].min() - 10, df['lon'].max() + 10 | |
# 図を作成(正方形、余白なし) | |
fig = plt.figure(figsize=(5, 5), frameon=False) | |
ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator()) | |
# 地図の範囲を設定 | |
ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=ccrs.PlateCarree()) | |
# 陸地を追加 | |
ax.add_feature(cfeature.LAND, facecolor='#E6F0C9') | |
ax.add_feature(cfeature.OCEAN, facecolor='#B3E5FC') | |
# データの緯度経度をプロット | |
for _, row in df.iterrows(): | |
ax.plot(row['lon'], row['lat'], marker='o', color='red', markersize=5, transform=ccrs.PlateCarree()) | |
# 軸を非表示に | |
ax.axis('off') | |
# 余白を削除 | |
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) | |
plt.margins(0,0) | |
# 画像を一時的に保存 | |
plt.savefig('temp_map.png', dpi=300, bbox_inches='tight', pad_inches=0) | |
plt.close() | |
# 画像を開いて正方形にクリッピング | |
with Image.open('temp_map.png') as img: | |
width, height = img.size | |
size = min(width, height) | |
left = (width - size) / 2 | |
top = (height - size) / 2 | |
right = (width + size) / 2 | |
bottom = (height + size) / 2 | |
img_cropped = img.crop((left, top, right, bottom)) | |
# 正方形にクリッピングした画像を保存 | |
img_cropped.save('map_plot.png') | |
# 一時ファイルを削除 | |
os.remove('temp_map.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment