sujingjhong.com


Python / 如何使用 python 繪製世界地圖

同學問到要怎麼使用 python 繪製世界地圖,並且呈現相關資料,就稍微研究了一下

主要使用:

  • altair: 繪製套件,可以製作可互動的圖表,好用
  • pycountry: 用來查詢國家的相關資料

使用的資料 winemag-data_first150k 是來自 kaggle

import pandas as pd
import numpy as np
import pycountry
def find_code_by_name(x):
    data = pycountry.countries.get(name=x) or pycountry.countries.get(official_name=x) or pycountry.countries.get(alpha_2=x)
    return int(data.numeric) if data is not None else np.nan

df = pd.read_csv('./winemag-data_first150k.csv')

df2 = df[['country', 'points']].groupby(by='country').mean().reset_index()
df2['id'] = df2.country.apply(find_code_by_name)
df2.head(10)

countrypointsid
0Albania88.0000008.0
1Argentina85.99609332.0
2Australia87.89247536.0
3Austria89.27674240.0
4Bosnia and Herzegovina84.75000070.0
5Brazil83.24000076.0
6Bulgaria85.467532100.0
7Canada88.239796124.0
8Chile86.296768152.0
9China82.000000156.0
import altair as alt
from vega_datasets import data

countries = alt.topo_feature(data.world_110m.url, 'countries')

base = alt.Chart(countries).mark_geoshape(fill='#666666',stroke='white')
points = alt.Chart(countries).mark_geoshape().encode(color='points:Q', tooltip=['country:N','points:Q']).transform_lookup(lookup='id', from_=alt.LookupData(df2, key='id', fields=['country','points']))

layers = alt.layer(base, points).project('equirectangular').properties(width=600, height=400).configure_view(stroke=None)
layers