Pandas - Plotly stacked area graph未产生预期结果

jjjwad0x  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(117)

我在使用Plotly时遇到了问题,并试图绘制一个堆叠面积图。我有以下数据框架,我们应该看到该图在负载列中达到200。

,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

但是当使用下面的代码来生成堆叠图时,图没有堆叠,并且似乎在2个特定点处下降到零。

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

当我单独看图表时,它看起来是正确的。

zazmityj

zazmityj1#

问题出在数据上。您需要小心一列或另一列缺少x值。
x轴的值必须由col1和col2的值共享。否则,当您为col1添加x值而不为col2添加x值时(或相反),默认值将向下移动到零,从而显示图中的结果。
尝试至少指定col1和col2共享的x轴上的所有点(0,15,16,30,90,106,116,尽管使用特定时间分辨率的时间序列并不是一个坏的做法,并坚持使用它,如1,2,3,4,5,...,114,115,116,并获得所有这些的负载值)。
一个工作示例(假设col1在16和106之间的负载值总是100,col2在30和90之间的负载值也是100)如下:

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()

其输出:

相关问题