python畫桑基圖
阿新 • • 發佈:2020-12-24
桑基圖
import pandas as pd df = pd.DataFrame({ '性別':['男','男','男', '女', '女', '女'], '熬夜原因':['打遊戲', '加班', '看劇', '打遊戲','加班', '看動漫'], '人數':[57,59,30,12,65,37] }) nodes = [] for i in range(2): values = df.iloc[:,i].unique() # pandas.core.series.Series # v2 = df.iloc[:5,:] # pandas.core.frame.DataFramefor value in values: dic = {} dic['name'] = value nodes.append(dic) links = [] for i in df.values: dic = {} dic['source'] = i[0] dic['target'] = i[1] dic['value'] = i[2] links.append(dic) from pyecharts.charts import Sankey from pyecharts import options as opts pic= ( Sankey(init_opts=opts.InitOpts(js_host="https://cdn.bootcss.com/echarts/4.4.0-rc.1/")) .add('', #圖例名稱 nodes, #傳入節點資料 links, #傳入邊和流量資料 linestyle_opt = opts.LineStyleOpts(opacity = 0.3, curve = 0.5, color = 'source'), # 標籤顯示位置 label_opts = opts.LabelOpts(position = 'right'), # 節點之前的距離 node_gap = 30, ) .set_global_opts(title_opts = opts.TitleOpts(title = '熬夜原因桑基圖')) ) if __name__ == '__main__': pic.render("index.html")
效果如下圖所示: