我试图用一个简单的例子来描绘一个Sankey图。下面的代码显示了我想要做的事情。
import pandas as pd
df = pd.DataFrame()
df['source'] = ['s1', 's2', 's3']
df['target'] = ['s2', 's3', 's4']
df['value'] = [2,2,1]
df['label'] = ['a','b','c']
df['color'] = ['rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)'] 'rgba(31, 119, 180, 0.8)']
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import *
init_notebook_mode(connected=True)
trace1 = {
"domain": {
"x": [0, 1],
"y": [0, 1]
},
"link": dict({
#"label": ['stream 1', '', '', ''],
"source": df['source'].dropna(axis=0, how='any'),
"target": df['target'].dropna(axis=0, how='any'),
"value": df['value'].dropna(axis=0, how='any'),
"color": df['color'].dropna(axis=0, how='any')
}),
"node": dict({
"color": df['color'],
"label": df['label'].dropna(axis=0, how='any'),
"line": {
"color": "black",
"width": 0.5
},
"pad": 0.5,
"thickness": 15
}),
"orientation": "h",
"type": "sankey",
"valueformat": ".0f",
"valuesuffix": "Ha"
}
data = Data([trace1])
layout = {
"font": {"size": 10},
}
fig = Figure(data=data, layout=layout)
iplot(fig, validate=False)
但是当我在ipython笔记本中运行时没有任何显示。我错过了什么?
答案 0 :(得分:2)
请记住,sankey图中的源和目标必须是数字而不是文本。 在您的情况下,最好为链接和节点创建单独的对象。 以下是基于您的数据的示例:
import pandas as pd
df_links = pd.DataFrame()
df_links['source'] = [0, 1, 2]
df_links['target'] = [1, 2, 3]
df_links['value'] = [2, 2, 1]
df_links['color'] = ['rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)']
df_nodes = pd.DataFrame()
df_nodes['label'] = ['s1','s2','s3','s4']
df_nodes['color'] = ['rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)', 'rgba(31, 119, 180, 0.8)']
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import *
init_notebook_mode(connected=True)
trace1 = {
"domain": {
"x": [0, 1],
"y": [0, 1]
},
"link": dict({
#"label": ['stream 1', '', '', ''],
"source": df['source'].dropna(axis=0, how='any'),
"target": df['target'].dropna(axis=0, how='any'),
"value": df['value'].dropna(axis=0, how='any'),
"color": df['color'].dropna(axis=0, how='any')
}),
"node": dict({
"color": df['color'].dropna(axis=0, how='any'),
"label": df['label'].dropna(axis=0, how='any'),
"line": {
"color": "black",
"width": 0.5
},
"pad": 0.5,
"thickness": 15
}),
"orientation": "h",
"type": "sankey",
"valueformat": ".0f",
"valuesuffix": "Ha"
}
layout = {
"font": {"size": 10},
}
fig = Figure(data=[trace1], layout=layout)
iplot(fig, validate=False)
请注意,某些在线服务会阻止内联代码的安全性,因此请先在自己的计算机上进行测试。