python可視化利器:pyecharts
前言
前面我們提及ggplot在R和Python中都是數據可視化的利器,在機器學習和數據分析領域得到了廣泛的應用。pyecharts結合了Python和百度開源的Echarts工具,基於其交互性和便利性得到了眾多開發者的認可。擁有如下的特點:
- 可集成至
Flask、Django等主流web框架 - 相較於
matplotlib等傳統繪圖庫,pyecharts語法更加簡潔,更加注重數據的呈現方式而非圖形細節 - 包含原生的百度地圖,方便繪制地理可視化圖形
本文主要整理自
pyecharts官網github文檔:https://github.com/pyecharts/pyecharts/
安裝
# pip安裝 $ pip(3) install pyecharts # 源碼安裝 $ git clone https://github.com/pyecharts/pyecharts.git $ cd pyecharts $ pip install -r requirements.txt $ python setup.py install # 或者執行 python install.py
簡單的實例
首先繪制第一個圖表:
from pyecharts.charts import Bar bar = Bar() bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]) bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90]) # render 會生成本地 HTML 文件,默認會在當前目錄生成 render.html 文件 # 也可以傳入路徑參數,如 bar.render("mycharts.html") bar.render() # pyechart所有方法均支持鏈式調用, 因此上面的代碼也可以改寫成如下形式 from pyecharts.charts import Bar bar = ( Bar() .add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]) .add_yaxis("商家A", [5, 20, 36, 10, 75, 90]) ) bar.render() # 使用options配置項添加主標題和副標題 from pyecharts.charts import Bar from pyecharts import options as opts bar = Bar() bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]) bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90]) bar.set_global_opts(title_opts=opts.TitleOpts(title="主標題", subtitle="副標題")) bar.render()
image.png
基本圖表
1. 柱狀圖
from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.commons.utils import JsCode from pyecharts.globals import ThemeType list2 = [ {"value": 12, "percent": 12 / (12 + 3)}, {"value": 23, "percent": 23 / (23 + 21)}, {"value": 33, "percent": 33 / (33 + 5)}, {"value": 3, "percent": 3 / (3 + 52)}, {"value": 33, "percent": 33 / (33 + 43)}, ] list3 = [ {"value": 3, "percent": 3 / (12 + 3)}, {"value": 21, "percent": 21 / (23 + 21)}, {"value": 5, "percent": 5 / (33 + 5)}, {"value": 52, "percent": 52 / (3 + 52)}, {"value": 43, "percent": 43 / (33 + 43)}, ] c = ( # 設置主題: 默認是黑紅風格, 其他風格大部分還不如黑紅風格好看 Bar(init_opts=opts.InitOpts()) # 新增x軸數據, 這里有五列柱狀圖 .add_xaxis( [ "名字很長的X軸標簽1", "名字很長的X軸標簽2", "名字很長的X軸標簽3", "名字很長的X軸標簽4", "名字很長的X軸標簽5", ] ) # 參數一: 系列名稱; 參數二: 系列數據; stack: 數據堆疊; category_gap: 柱間距離 .add_yaxis("product1", list2, stack="stack1", category_gap="50%") .add_yaxis("product2", list3, stack="stack1", category_gap="50%") # set_series_opts系列配置項,可配置圖元樣式、文字樣式、標簽樣式、點線樣式等; 其中opts.LabelOpts指標簽配置項 .set_series_opts( label_opts=opts.LabelOpts( position="right", # 數據標簽的位置 formatter=JsCode( # 標簽內容的格式器, 這里展示了百分比 "function(x){return Number(x.data.percent * 100).toFixed() + '%';}" ), ) ) 