就是這麼簡單!Pyecharts 繪製可視化地圖

人生苦短,快學 Python!

Pyecharts 是一個用於生成 Echarts 圖表的類庫。Echarts 是百度開源的一個數據可視化 JS 庫。用 Echarts 生成的圖可視化效果非常棒,pyecharts 是爲了與 Python 進行對接,方便在 Python 中直接使用數據生成圖。

Pyecharts 繪製地圖如此輕鬆,幾行代碼搞定多種形式的數據地圖。

安裝

首先需要安裝 python 第三方包 -- pyecharts, 目前最新版本爲 1.8.1。

pip install pyecharts

自從 v0.3.2 開始,爲了縮減項目本身的體積以及維持 pyecharts項目的輕量化運行,pyecharts將不再自帶地圖 js 文件。如用戶需要用到地圖圖表,可自行安裝對應的地圖文件包。下面介紹如何安裝。

選擇自己需要安裝地圖相關的擴展包。

pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg
pip install echarts-china-counties-pypkg
pip install echarts-china-misc-pypkg
pip install echarts-united-kingdom-pypkg

可以選擇豆瓣源或清華源加速安裝。

pip install pyecharts -i http://pypi.douban.com/simple 
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple echarts-countries-pypkg

pyecharts 版本 v0.5.x 和 v1 間不兼容,v1 是一個全新的版本,語法也有很大不同。

查看 pyecharts 版本。

import pyecharts
print(pyecharts.__version__)

做好準備後,就可以開始繪圖了。如果你是新手,對 pyehcarts 還有些陌生,可以參見官方 5 分鐘上手:
https://pyecharts.org/#/zh-cn/quickstart?id=_5 - 分鐘上手

繪製地圖

Pyehcarts 共有有四種地理圖表,

一、Map

以星巴克門店在全球的分佈爲例。本例數據來源 Kaggle 星巴克數據:https://www.kaggle.com/starbucks/store-locations

也可公衆號後臺回覆【星巴克】獲取。

數據樣例:

from pyecharts.charts import Map
from pyecharts import options as opts
from pyecharts.globals import ThemeType, CurrentConfig

CurrentConfig.ONLINE_HOST = 'C:/python/pyecharts-assets-master/assets/'
# 參考 https://github.com/pyecharts/pyecharts-assets

df = starbuck['English']
data = df.value_counts()
datas = [(i, int(j)) for i, j in zip(data.index, data.values)]

# 實例化一個Map對象
map_ = Map(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION))

# 世界地圖
map_.add(series_)

# 設置系列配置項
map_.set_series_opts(label_opts=opts.LabelOpts(is_show=False))   # 不顯示label
# 設置全局配置項
map_.set_global_opts(
     title_opts=opts.TitleOpts(title="星巴克門店數量在全球分佈", 
                               pos_left='40%', 
                               pos_top='10'),   # 調整title位置
     legend_opts=opts.LegendOpts(is_show=False),
     visualmap_opts=opts.VisualMapOpts(
         max_=13608, 
         min_=1, 
         is_piecewise=True,
       pieces=[{"max": 9, "min": 1, "label""1-9""color""#00FFFF"},
                 {"max": 99, "min": 10, "label""10-99""color""#FF69B4"},
                 {"max": 499, "min": 100, "label""100-499""color""#0000FF"},
                 {"max": 999, "min": 500, "label""500-999""color""#00BFFF"},
                 {"max": 2000, "min": 1000, "label""1000-2000""color""#228B22"},
                 {"max": 3000, "min": 2000, "label""2000-3000""color""#FF0000"},
                 {"max": 20000, "min": 10000, "label"">=10000""color""#FFD700"}
                ] # 分段  添加圖例註釋和顏色
     )
)
# 渲染在網頁上   有交互性
map_.render('星巴克門店在全球的分佈.html')

輸出

繪圖步驟:

1、創建實例

Map(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION))

theme: pyecharts 內置提供了 10+ 種不同的風格, 參見
https://pyecharts.org/#/zh-cn/themes

2、添加數據

.add()添加了數據。

3、設置系列配置項

.set_series_opts()

https://pyecharts.org/#/zh-cn/series_options

除了在.add()中設置部分配置項外,就是使用.set_series_opts()配置圖元樣式、文字樣式、標籤樣式、點線樣式等。

4、設置全局配置項

.set_global_opts() 配置標題、動畫、座標軸、圖例等。
https://pyecharts.org/#/zh-cn/global_options

本實例中:

5、生成的地圖以 html 格式保存

.render()將生成的地圖以html格式保存。

二、Geo

Geo 圖類型,使用type_: str = "scatter" 參數控制。

scatter, effectScatter, heatmap, lines4 種。

from pyecharts.globals import GeoType    
GeoType.GeoType.EFFECT_SCATTER,GeoType.HEATMAP,GeoType.LINES

1、動態漣漪散點圖 effectScatter

V1 版本開始支持鏈式調用,本例數據可後臺回覆【星巴克】獲取。

數據樣例:

import pandas as pd
from pyecharts.globals import ThemeType, CurrentConfig, GeoType
from pyecharts import options as opts
from pyecharts.charts import Geo

CurrentConfig.ONLINE_HOST = 'C:/python/pyecharts-assets-master/assets/'
# pandas讀取csv文件數據
df = pd.read_csv('directory2.csv'encoding='utf-8')['城市']
data = df.value_counts()
#自定義各城市的經緯度
# geo_cities_coords = {df.iloc[i]['城市']:[df.iloc[i]['經度'],df.iloc[i]['緯度']] for i in range(len(df))}

datas = [(i, int(j)) for i, j in zip(data.index, data.values)]
print(datas)

geo = (Geo(init_opts=opts.InitOpts(width='1000px', 
                                   height='600px', 
                                   theme=ThemeType.PURPLE_PASSION),
           is_ignore_nonexistent_coord = True)
       .add_schema(maptype='china', 
                   label_opts=opts.LabelOpts(is_show=True))   # 顯示label  省名
       .add('門店數量', 
            data_pair=datas, 
            type_=GeoType.EFFECT_SCATTER, 
            symbol_size=8,
            # geo_cities_coords=geo_cities_coords
           )
       .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
       .set_global_opts(
           title_opts=opts.TitleOpts(title='星巴克門店在中國的分佈'),
           visualmap_opts=opts.VisualMapOpts(max_=550,
                                             is_piecewise=True,
                                             pieces=[
                     {"max": 50, "min": 0, "label""0-50""color""#708090"},
                     {"max": 100, "min": 51, "label""51-100""color""#00FFFF"},
                     {"max": 200, "min": 101, "label""101-200""color""#FF69B4"},
                     {"max": 400, "min": 201, "label""201-400""color""#FFD700"},
                     {"max": 800, "min": 600, "label""600-800""color""#FF0000"},])
       )
      )

geo.render("星巴克門店在中國的分佈.html")

輸出

Geo 新增座標點

# 新增一個座標點
.add_coordinate(    
    # 座標地點名稱    
    name: str,     
    # 經度    
    longitude: Numeric,     
    # 緯度    
    latitude: Numeric, )
# 新增 json 文件格式的座標數據
.add_coordinate_json(
    # json 文件格式的座標數據
    # 格式如下
    # {
    #   "阿城": [126.58, 45.32],
    #   "阿克蘇": [80.19, 41.09]
    # }
    json_file: str # 座標文件路徑
)

2、熱力圖 heatmap

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType
CurrentConfig.ONLINE_HOST = 'C:/python/pyecharts-assets-master/assets/'

# pandas讀取csv文件數據
df = pd.read_csv('directory2.csv'encoding='utf-8')['城市']
data = df.value_counts()

datas = [(i, int(j)) for i, j in zip(data.index, data.values)]
print(datas)
geo = (
    Geo(init_opts=opts.InitOpts(width='1000px', 
                                height='600px', 
                                theme=ThemeType.DARK),
        is_ignore_nonexistent_coord=True)
    .add_schema(maptype="china")                       #maptype選擇地圖種類
    .add(series_,      # 系列名稱
         data_pair=datas,          # 數據項 (座標點名稱,座標點值)
         blur_size=20,
         symbol_size= 5,
         type_=ChartType.HEATMAP  #類型選爲熱力圖
         )
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(max_=800,is_piecewise=True),
        title_opts=opts.TitleOpts(title="星巴克門店在中國的分佈熱力圖"))
)
geo.render( '星巴克門店在中國的分佈熱力圖.html')

輸出

3、動態軌跡圖 lines

pyecharts 可以生成地理空間流動圖,用來表示航班數量、人口流動等等。

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.faker import Faker
from pyecharts.globals import ChartType, SymbolType, CurrentConfig
import  random

datas = []
for _ in range(6):
    datas.append(tuple(random.sample(Faker.provinces, 2)))
    
CurrentConfig.ONLINE_HOST = 'C:/python/pyecharts-assets-master/assets/'
geo = (
    Geo(init_opts=opts.InitOpts(width='1000px', 
                                height='600px', 
                                theme=ThemeType.CHALK))
    .add_schema(
        maptype="china",
        itemstyle_opts=opts.ItemStyleOpts(color="#323c48"border_color="#111"),
        label_opts=opts.LabelOpts(is_show=True)
    )
    .add(
        "",
        [list(z) for z in zip(Faker.provinces, Faker.values())],
        type_=ChartType.EFFECT_SCATTER,
        color="white",
    )
    .add(
        "出差",
        data_pair = datas,
        type_=ChartType.LINES,
        effect_opts=opts.EffectOpts(
            symbol=SymbolType.DIAMOND, symbol_size=6, color="blue"
        ),
        linestyle_opts=opts.LineStyleOpts(curve=0.2),
    )
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(title_opts=opts.TitleOpts(title="動態軌跡圖"))
    .render("動態軌跡圖.html")
)

輸出

如果需要再添加一個其他類別的動態軌跡,只需在鏈式中添加:

.add('旅遊',
     [('上海','拉薩'),('拉薩','大理'),('大理','成都'),('成都','海口')],
     type_=ChartType.LINES,
     effect_opts=opts.EffectOpts(
         symbol=SymbolType.ARROW, symbol_size=6, color="orange"),
     linestyle_opts=opts.LineStyleOpts(curve=0.5)
    )

輸出如下,可以點擊圖例來篩選類別。

這邊用到兩個配置項:

4、三維地圖

from pyecharts import options as opts
from pyecharts.charts import Map3D
from pyecharts.globals import ChartType
from pyecharts.commons.utils import JsCode

c = (
    Map3D(init_opts=opts.InitOpts(width='1000px', 
                                height='600px', 
                                theme=ThemeType.VINTAGE))
    # 地圖類型
    .add_schema(
        itemstyle_opts=opts.ItemStyleOpts( # 圖形的顏色
            color="#00BFFF"# 或 'rgb(128, 128, 128)'
            opacity=1, # 圖形透明度
            border_width=0.8, # 描邊寬度
            border_color="#708090"# 描邊顏色
        ),
        # Map3D 的 Label 設置
        map3d_label=opts.Map3DLabelOpts(
            is_show=False,
            formatter=JsCode("function(data){return data.name + " " + data.value[2];}"),
        ),
        
        # 高亮標籤配置項
        emphasis_label_opts=opts.LabelOpts(
            is_show=False,
            color="#fff",
            font_size=10,
            background_color="rgba(0,23,11,0)",
        ),
        
        # 光照相關的設置。
        light_opts=opts.Map3DLightOpts(
            main_color="#fff",
            main_intensity=1.2,
            main_shadow_quality="high",
            is_main_shadow=False,
            main_beta=10,
            ambient_intensity=0.3,
        ),
    )
    .add(
        series_,
        data_pair=datas,
        # 疊加圖的類型
        type_=ChartType.BAR3D,
        bar_size=1,
        
        # 三維地圖中三維圖形的着色效果。
        shading="lambert",
        label_opts=opts.LabelOpts(
            is_show=False,
            formatter=JsCode("function(data){return data.name + ' ' + data.value[2];}"),
        ),
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="星巴克門店在中國的分佈3D圖"))
    .render("map3d_with_bar3d.html")
)

輸出

本例中的主要參數說明:

.add_schema()

地圖類型設置,參考 pyecharts.datasets.map_filenames.json 文件

.add()

5、Globe 地圖

數據來源是 pyecharts 自帶的全球人口數據。

import pyecharts.options as opts
from pyecharts.charts import MapGlobe
from pyecharts.faker import POPULATION
from pyecharts.globals import ThemeType

data = [for _, x in POPULATION[1:]]
low, high = min(data), max(data)

c = (
    MapGlobe(init_opts=opts.InitOpts(theme=ThemeType.DARK))
    .add_schema()
    .add(
        maptype="world",
        series_,
        data_pair=POPULATION[1:],
        is_map_symbol_show=False,
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(
            min_=low,
            max_=high,
            range_text=["max""min"],
            is_calculable=True,
            range_color=["lightskyblue""yellow""orangered"],
        )
    )
    .render("map_globe_base.html")
)

輸出

本文到此結束,總體來說 Pyecharts 地圖繪圖還是比較友好,在不需要多麼炫酷的配置前提下,只需要將輸入數據格式和類型弄清楚,其餘默認配置即可。

對地圖樣式有一定要求時,只需要根據官網上的配置信息調整全局配置項和系列配置項即可。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/jPPD5kidDJ3WmsOFkkoPWg