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

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

January 10, 2021

同學問到要怎麼使用 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)

country points id
0 Albania 88.000000 8.0
1 Argentina 85.996093 32.0
2 Australia 87.892475 36.0
3 Austria 89.276742 40.0
4 Bosnia and Herzegovina 84.750000 70.0
5 Brazil 83.240000 76.0
6 Bulgaria 85.467532 100.0
7 Canada 88.239796 124.0
8 Chile 86.296768 152.0
9 China 82.000000 156.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

給我讚!

相關文章


© 2019-2021 Su Jing Jhong 版權所有 創用 CC 授權條款