
來(lái)源:數(shù)據(jù)STUDIO
作者:云朵君
Pyecharts 是一個(gè)用于生成 Echarts 圖表的類(lèi)庫(kù)。Echarts 是百度開(kāi)源的一個(gè)數(shù)據(jù)可視化 JS 庫(kù)。用 Echarts 生成的圖可視化效果非常棒,pyecharts 是為了與 Python 進(jìn)行對(duì)接,方便在 Python 中直接使用數(shù)據(jù)生成圖。
Pyecharts繪制地圖如此輕松,幾行代碼搞定多種形式的數(shù)據(jù)地圖。
首先需要安裝python第三方包 -- pyecharts, 目前最新版本為1.8.1。
pip install pyecharts
自從 v0.3.2 開(kāi)始,為了縮減項(xiàng)目本身的體積以及維持 pyecharts項(xiàng)目的輕量化運(yùn)行,pyecharts將不再自帶地圖 js 文件。如用戶需要用到地圖圖表,可自行安裝對(duì)應(yīng)的地圖文件包。下面介紹如何安裝。
選擇自己需要安裝地圖相關(guān)的擴(kuò)展包。
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 是一個(gè)全新的版本,語(yǔ)法也有很大不同。
查看pyecharts版本。
import pyecharts print(pyecharts.__version__)
做好準(zhǔn)備后,就可以開(kāi)始繪圖了。如果你是新手,對(duì)pyehcarts還有些陌生,可以參見(jiàn)官方5分鐘上手:
Pyehcarts共有有四種地理圖表,
以星巴克門(mén)店在全球的分布為例。本例數(shù)據(jù)來(lái)源Kaggle星巴克數(shù)據(jù):https://www.kaggle.com/starbucks/store-locations
數(shù)據(jù)樣例:
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)] # 實(shí)例化一個(gè)Map對(duì)象 map_ = Map(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION)) # 世界地圖 map_.add(series_name="門(mén)店數(shù)量", data_pair=datas, maptype="world") # 設(shè)置系列配置項(xiàng) map_.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) # 不顯示label # 設(shè)置全局配置項(xiàng) map_.set_global_opts(
title_opts=opts.TitleOpts(title="星巴克門(mén)店數(shù)量在全球分布",
pos_left='40%',
pos_top='10'), # 調(diào)整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"}
] # 分段 添加圖例注釋和顏色 )
) # 渲染在網(wǎng)頁(yè)上 有交互性 map_.render('星巴克門(mén)店在全球的分布.html')
輸出
1、創(chuàng)建實(shí)例
Map(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION))
創(chuàng)建實(shí)例并初始化配置。
可配置圖表寬度、高度、渲染風(fēng)格、標(biāo)題、主題、背景顏色等,詳情參見(jiàn)下面連接
https://pyecharts.org/#/zh-cn/global_options?id=initopts:初始化配置項(xiàng)
theme: pyecharts內(nèi)置提供了10+ 種不同的風(fēng)格, 參見(jiàn)
https://pyecharts.org/#/zh-cn/themes
2、添加數(shù)據(jù)
.add()添加了數(shù)據(jù)。
3、設(shè)置系列配置項(xiàng)
.set_series_opts()
https://pyecharts.org/#/zh-cn/series_options
除了在.add()中設(shè)置部分配置項(xiàng)外,就是使用.set_series_opts()配置圖元樣式、文字樣式、標(biāo)簽樣式、點(diǎn)線樣式等。
4、設(shè)置全局配置項(xiàng)
.set_global_opts() 配置標(biāo)題、動(dòng)畫(huà)、坐標(biāo)軸、圖例等。
https://pyecharts.org/#/zh-cn/global_options
本實(shí)例中:
5、生成的地圖以html格式保存
.render()將生成的地圖以html格式保存。
Geo 圖類(lèi)型,使用type_: str = "scatter" 參數(shù)控制。
有 scatter, effectScatter, heatmap, lines4 種。
from pyecharts.globals import GeoType GeoType.GeoType.EFFECT_SCATTER,GeoType.HEATMAP,GeoType.LINES
1、動(dòng)態(tài)漣漪散點(diǎn)圖 effectScatter
V1 版本開(kāi)始支持鏈?zhǔn)秸{(diào)用。
數(shù)據(jù)樣例:
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文件數(shù)據(jù) df = pd.read_csv('directory2.csv', encoding='utf-8')['城市']
data = df.value_counts() #自定義各城市的經(jīng)緯度 # geo_cities_coords = {df.iloc[i]['城市']:[df.iloc[i]['經(jīng)度'],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('門(mén)店數(shù)量',
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='星巴克門(mén)店在中國(guó)的分布'),
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("星巴克門(mén)店在中國(guó)的分布.html")
輸出
Geo新增坐標(biāo)點(diǎn)# 新增一個(gè)坐標(biāo)點(diǎn)
.add_coordinate(
# 坐標(biāo)地點(diǎn)名稱
name: str,
# 經(jīng)度
longitude: Numeric,
# 緯度
latitude: Numeric, )
# 新增 json 文件格式的坐標(biāo)數(shù)據(jù)
.add_coordinate_json(
# json 文件格式的坐標(biāo)數(shù)據(jù)
# 格式如下
# {
# "阿城": [126.58, 45.32],
# "阿克蘇": [80.19, 41.09]
# }
json_file: str # 坐標(biāo)文件路徑
)
2、熱力圖heatmapfrom 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文件數(shù)據(jù)
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選擇地圖種類(lèi)
.add(series_name="門(mén)店數(shù)量", # 系列名稱
data_pair=datas, # 數(shù)據(jù)項(xiàng) (坐標(biāo)點(diǎn)名稱,坐標(biāo)點(diǎn)值)
blur_size=20,
symbol_size= 5,
type_=ChartType.HEATMAP #類(lèi)型選為熱力圖
)
.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="星巴克門(mén)店在中國(guó)的分布熱力圖"))
)
geo.render( '星巴克門(mén)店在中國(guó)的分布熱力圖.html')
輸出
3、動(dòng)態(tài)軌跡圖lines
pyecharts可以生成地理空間流動(dòng)圖,用來(lái)表示航班數(shù)量、人口流動(dòng)等等。
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="動(dòng)態(tài)軌跡圖"))
.render("動(dòng)態(tài)軌跡圖.html")
)
輸出
如果需要再添加一個(gè)其他類(lèi)別的動(dòng)態(tài)軌跡,只需在鏈?zhǔn)街刑砑樱?/span>
.add('旅游',
[('上海','拉薩'),('拉薩','大理'),('大理','成都'),('成都','???)],
type_=ChartType.LINES,
effect_opts=opts.EffectOpts(
symbol=SymbolType.ARROW, symbol_size=6, color="orange"),
linestyle_opts=opts.LineStyleOpts(curve=0.5)
)
輸出如下,可以點(diǎn)擊圖例來(lái)篩選類(lèi)別。
這邊用到兩個(gè)配置項(xiàng):
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))
# 地圖類(lèi)型 .add_schema(
itemstyle_opts=opts.ItemStyleOpts( # 圖形的顏色 color="#00BFFF", # 或 'rgb(128, 128, 128)' opacity=1, # 圖形透明度 border_width=0.8, # 描邊寬度 border_color="#708090", # 描邊顏色 ),
# Map3D 的 Label 設(shè)置 map3d_label=opts.Map3DLabelOpts(
is_show=False,
formatter=JsCode("function(data){return data.name + " " + data.value[2];}"),
),
# 高亮標(biāo)簽配置項(xiàng) emphasis_label_opts=opts.LabelOpts(
is_show=False,
color="#fff",
font_size=10,
background_color="rgba(0,23,11,0)",
),
# 光照相關(guān)的設(shè)置。 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_name="門(mén)店數(shù)量",
data_pair=datas,
# 疊加圖的類(lèi)型 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="星巴克門(mén)店在中國(guó)的分布3D圖"))
.render("map3d_with_bar3d.html")
)
輸出
本例中的主要參數(shù)說(shuō)明:
.add_schema()
地圖類(lèi)型設(shè)置,參考pyecharts.datasets.map_filenames.json 文件
.add()
5、Globe地圖
數(shù)據(jù)來(lái)源是pyecharts自帶的全球人口數(shù)據(jù)。
import pyecharts.options as opts from pyecharts.charts import MapGlobe from pyecharts.faker import POPULATION from pyecharts.globals import ThemeType
data = [x 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_name="World Population",
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")
)
輸出
本文到此結(jié)束,總體來(lái)說(shuō)Pyecharts地圖繪圖還是比較友好,在不需要多么炫酷的配置前提下,只需要將輸入數(shù)據(jù)格式和類(lèi)型弄清楚,其余默認(rèn)配置即可。
對(duì)地圖樣式有一定要求時(shí),只需要根據(jù)官網(wǎng)上的配置信息調(diào)整全局配置項(xiàng)和系列配置項(xiàng)即可。
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無(wú)論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫(kù)管理中,“大表” 始終是性能優(yōu)化繞不開(kāi)的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫(kù)表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動(dòng)態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開(kāi)始提取前,需先判斷 TIF 文件的類(lèi)型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價(jià)值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫(kù)表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫(kù))處理 Excel 數(shù)據(jù)時(shí),“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場(chǎng)景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤(pán)手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對(duì)象的 text 與 content:區(qū)別、場(chǎng)景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請(qǐng)求開(kāi)發(fā)時(shí)(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價(jià)值的核心操盤(pán)手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫(kù)表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請(qǐng)求工具對(duì)比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請(qǐng)求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問(wèn)題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)時(shí)的科學(xué)計(jì)數(shù)法問(wèn)題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價(jià)值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營(yíng)問(wèn)題、提升執(zhí)行效率的核心手段,其價(jià)值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過(guò)程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營(yíng)銷(xiāo)案例:數(shù)據(jù)驅(qū)動(dòng)下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見(jiàn)頂” 的當(dāng)下,精準(zhǔn)營(yíng)銷(xiāo)成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價(jià)值 在數(shù)據(jù)驅(qū)動(dòng)決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類(lèi)分析:從操作實(shí)踐到業(yè)務(wù)價(jià)值挖掘 在數(shù)據(jù)分析場(chǎng)景中,聚類(lèi)分析作為 “無(wú)監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計(jì)模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價(jià)值導(dǎo)向 統(tǒng)計(jì)模型作為數(shù)據(jù)分析的核心工具,并非簡(jiǎn)單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10