Google Colaboratory でPlotlyのサンキーダイアグラム

やったこと

こちらの記事の内容をパクらせていただきましたが、collabで動かすように一部変更しました。

[参考]
Python plotlyを用いてSankey Diagram(サンキーダイアグラム)を作成する

主な変更点としては2点。

・plotly.plotly が非推奨になったらしいので chart_studio.plotly に変更
・offline は利用せず graph_objects を利用して描画

コード

chart_studio は標準ではインストールされてないみたいなので自分で入れる

pip install chart_studio
# 元々はimport plotly.plotly as py だったが、plotly.plotly は非推奨になったというエラーによるchart_studio.plotlyに変更
import chart_studio.plotly as py
import plotly.graph_objects as go

data = dict(
   type='sankey',
   node = dict(
     pad = 15,
     thickness = 20,
     line = dict(
       color = "black",
       width = 0.5
     ),
     label = ["い", "ろ", "は", "に", "ほ", "へ"], #各nodeを作成 
     # color = ["blue", "blue", "green", "green", "yellow", "yellow"] #色を指定します。
   ),
   link = dict(
     source = [0,1,1,0,2,3,3], #sourceは出発元のnode  
     target = [2,2,3,3,4,4,5], #targetは到着先のnode  
     value = [8,1,3,2,9,3,2] #流量
 ))

layout =  dict(
   title = "Sankey Diagram はじめました",
   font = dict(
     size = 10
   )
)

fig = dict(data=[data], layout=layout)

view = go.Figure(fig)
view.show(renderer="colab")

この記事が気に入ったらサポートをしてみませんか?