Pandas - Plotly stacked area graph not producing the desired results

Viewed 107

I'm having trouble with Plotly and trying to graph a stacked area graph. I have the following data frame and we should see the graph reaching 200 in the load column.

,Group,Label,time,load
0,Group,col1,0.0,0.0
1,Group,col1,15.0,0.0
2,Group,col1,16.0,100.0
3,Group,col1,106.0,100.0
4,Group,col1,116.0,0.0
5,Group,col2,0.0,0.0
6,Group,col2,0.0,0.0
7,Group,col2,30.0,100.0
8,Group,col2,90.0,100.0
9,Group,col2,100.0,0.0

but when using the following code to produce a stacked graph, the graphs are not stacked and seems to be dropping to zero at 2 particular points.

fig = px.area(df, x="time", y="load", color="Label")
fig.show()

enter image description here

When i look at the graphs individually it looks correct.

enter image description here

enter image description here

1 Answers

Problem is with data. You need to be careful with missing x values for one or another column.

The values for the x axis have to be shared by both col1 and col2 values. Otherwise, when you add an x value for col1 and not for col2 (or the other way round), the value by default travels down to zero, thus showing the results you have in your plot.

Try to specify at leat all the points in x axis both col1 and col2 share (0,15,16,30,90,106,116 although is not a bad practice with time series using a specific time resolution and stick with it as in 1,2,3,4,5,..., 114, 115, 116 and get the load value for all of them).

A working example (assuming load values for col1 between 16 and 106 are always 100 and for col2 load values between 30 and 90 are also 100) would be:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO(''',Group,Label,time,load
0,Group,col1,0.0,0.0
1,Group,col1,15.0,0.0
2,Group,col1,16.0,100.0
3,Group,col1,30.0,100.0
4,Group,col1,90.0,100.0
5,Group,col1,100.0,100.0
6,Group,col1,106.0,100.0
7,Group,col1,116.0,0.0


8,Group,col2,0.0,0.0
9,Group,col2,15.0,0.0
10,Group,col2,16.0,0.0
12,Group,col2,30.0,100.0
13,Group,col2,90.0,100.0
14,Group,col2,100.0,0.0
15,Group,col2,106.0,0.0
16,Group,col2,116.0,0.0

''')

df= pd.read_csv(TESTDATA, sep=",")


import plotly.express as px
fig = px.area(df, x="time", y="load", color="Label")
fig.show()

which outputs:

enter image description here

Related