sankey图的图为空

问题描述

Empty plot

我是python / spyder的新手,我正在尝试制作sankey图,但图中未包含任何数据,只是空白。我发现我需要从数据框转换为列表,但这并没有帮助,并且图表仍然为空。我将其保持得非常简单,并且几乎直接从plotly的指南中复制了它,并且只是导入了我自己的数据。 这是我的代码,我刚刚删除文件路径。 谁能告诉我我的错误是什么? 编辑以添加xlsx文件的图像:xlsx file
编辑新的Plot的2张图片

import plotly.graph_objects as go
import pandas as pd
# go.renderers.default = "browser"
df = pd.read_excel (r'C:\filepath\data.xlsx') 

labels=pd.DataFrame(df,columns= ['Label'])
label_list=labels.values.tolist()
sources=pd.DataFrame(df,columns= ['Source'])
source_list=sources.values.tolist()
targets=pd.DataFrame(df,columns= ['Target'])
target_list=targets.values.tolist()
values=pd.DataFrame(df,columns= ['Value'])
value_list=values.values.tolist()


fig = go.figure(data=[go.Sankey(
    node = dict(
      pad = 15,thickness = 20,line = dict(color = "black",width = 0.5),label = label_list,color = "blue"
    ),link = dict(
      source = source_list,target = target_list,value = value_list
  ))])

fig.update_layout(title_text="Basic Sankey Diagram",font_size=10)
fig.show()

解决方法

请检查随机数据段。 sankey

当您从excel阅读时,它仅给您dataframe。您无需再次将其存储到dataframe

您无需将其转换为list。您可以将dataframe列直接传递到label,source,value and target

import plotly.graph_objects as go
import pandas as pd
df = pd.read_excel (r'data.xlsx')
print(df)
"""
  Label  Source  Target  Value
0    A1       0       2      8
1    A2       1       3      4
2    B1       0       3      2
3    B2       2       4      8
4    C1       3       4      4
5    C2       3       5      2
"""
fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,thickness = 20,line = dict(color = "black",width = 0.5),label = df['Label'],color = "blue"
    ),link = dict(
      source = df['Source'],target = df['Target'],value = df['Value']
  ))])

fig.update_layout(title_text="Basic Sankey Diagram",font_size=10)
fig.show()

提示

您的labels_list,source_list,target_list,value_list不是list。这是nested list

如果要将dataframe列存储到列表中,则可以这样做,

labels_list=df['Label'].tolist()
source_list=df['Source'].tolist()
target_list=df['Target'].tolist()
value_list=df['Value'].tolist()

有关更多详细信息,请参阅 Sankey Diagram Plotly