我想生成一个熊猫数据框的分组数据图(或子图)。我认为这应该是基本的东西-我只是缺少一些东西。我有从下面提供的数据示例准备的堆叠输入数据。我想为每个上层数据生成如下图的图表:
在这里,我有一些示例数据(我在下面粘贴了我正在使用的示例.csv数据)。这些数据以数据信息,时间,数据的“堆叠”形式出现。数据信息描述了特定数据点的类别和子类别。
import pandas as pd
import re
import matplotlib.pyplot as plt
df=pd.read_csv('.....TestData.csv',index_col='T')
df=df.stack(0).reset_index(1)
df.columns=['fullType','data']
#And at this point, this is pretty much the form of my actual data
#So I split it up a bit to try to get columns for different data groupings
regexStr='~'
def upperParser(row):
label=re.split(regexStr,row['fullType'])
return label[1]
def lowerParser(row):
label=re.split(regexStr,row['fullType'])
return label[2]
df['upperLevel']=df.apply(upperParser,axis=1)
df['lowerLevel']=df.apply(lowerParser,axis=1)
df['time']=df.index
df=df.reset_index(drop=True)
plt.figure();
df.plot();
#And here is one of many attempts... I just seem to be missing something that should be simple:
for grp in df.groupby('upperLevel'):
for key,grp in df.groupby('lowerLevel'):
plt.plot(x='time',y=grp['data'],label=key)
plt.show()
任何方向都将不胜感激。我不关心尝试保留任何特定形式。我的最终目标是使所有upperLevel类别的曲线图(表示A =(0,1),B =(0,2)),并使用mpl3d查看底层副区(像这样,但与每个子类别1,2, 3堆叠为子图)。但首先我想。
样本数据:
T Col~A~1~ Col~A~2~ Col~A~3~ Col~B~1~ Col~B~2~ Col~B~3~
1 1 0.5 0.5 0.5 0.25 0.25
1.5 2 1 1 1 0.5 0.5
2 3 1.5 0.5 1.5 0.75 0.25
2.5 4 2 1 2 1 0.5
3 5 2.5 0.5 2.5 1.25 0.25
3.5 6 3 1 3 1.5 0.5
4 7 3.5 0.5 3.5 1.75 0.25
4.5 8 4 1 4 2 0.5
5 9 4.5 0.5 4.5 2.25 0.25
5.5 10 5 1 5 2.5 0.5
6 11 5.5 0.5 5.5 2.75 0.25
6.5 12 6 1 6 3 0.5
7 13 6.5 0.5 6.5 3.25 0.25
7.5 14 7 1 7 3.5 0.5
8 15 7.5 0.5 7.5 3.75 0.25
8.5 16 8 1 8 4 0.5
9 17 8.5 0.5 8.5 4.25 0.25
9.5 18 9 1 9 4.5 0.5
10 19 9.5 0.5 9.5 4.75 0.25
一些提示:
df.groupby()
返回(group_name, group)
元组,因此在尝试遍历各组时要小心。pyplot
如果pandas
绘图方法涵盖了所需的绘图,则您不想手动使用。pandas
绘制方法通常会在要绘制的数据框中为每一列生成一条单独的线,因此,如果可以重新排列数据以将数据源放在单独的列中,则可以轻松获取所需的图。pandas
默认情况下,绘图方法会将数据框的索引用作x轴。也就是说,您可以使用以下方法生成所需的图:
for group_name, grp in df.groupby('upperLevel'):
plot_table = grp.pivot(index='time', columns='lowerLevel', values='data')
plot_table.plot()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句