pythonplotly-expresssunburst-diagram

How to read values from df into plotly express sunburst?


I have a single-row csv file that I'm reading into a dataframe, and trying to export to a plotly express Sunburst graph. I'm having trouble getting the values from the df into the graph.

JobCompletion.csv:
Total,Completed,Unsuccessful,Failed,Timeout,Cancelled
188844,166718,22124,1018,20,21086

df = pd.read_csv("JobCompletion.csv")

df
     Total  Completed  Unsuccessful  Failed  Timeout  Cancelled
0   188844     166718         22124    1018       20      21086

My "names" will always be as above, so I can hardcode them into variables:

categories = ["Total","Completed","Unsuccessful","Failed","Timeout","Cancelled"]
parent = ["","Total","Total","Unsuccessful","Unsuccessful","Unsuccessful"]

If I hard code an array of values:

value = [18844,166718,22124,1018,20,21086]

Then the below code works for my sunburst:

fig = px.sunburst(df,
                  names = categories,
                  parents = parent,
                  values = value, # here's where I need help
                  branchvalues = 'total')

But, I need to dynamically read in the values from my csv/df into the graph. My entry-level knowledge of plotly has me scratching my head getting the values out of the dataframe. Any help is most appreciated.


Solution

  • You can get the first row from your df as a list with df.loc[0, :].values.tolist(). You can adjust the row you get as needed by changing the 0.

    If you want to do the same for your column names instead of using the hard coded list you could also do df.columns.tolist()