Python Pandas Matplotlib Plot由单列中定义的类型值着色

时间:2014-12-27 05:13:36

标签: python matplotlib pandas

我有以下格式的数据:

import pandas as ps
table={'time':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],\
    'data':[1,1,2,2,2,1,2,3,4,5,1,2,2,2,3],\
    'type':['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']}
df=ps.DataFrame(table,columns=['time','data','type']

我想将数据绘制为作为一条线连接的时间函数,但我希望每一行都是唯一类型的单独颜色。在此示例中,结果将是三行:每种类型a,b和c的数据(时间)行。任何指导都表示赞赏。

我无法使用此数据生成一行 - pandas.scatter将生成一个图,而pandas.plot则不会。我一直在搞乱循环,为每种类型制作一个情节,但我还没有找到一种直接的方法来做到这一点。我的数据通常包含未知数量的唯一“类型”。 pandas和/或matpltlib是否有办法创建这种类型的情节?

2 个答案:

答案 0 :(得分:3)

如果所有内容都已正确索引,Pandas绘图功能将允许您执行此操作。但是,有时直接使用matplotlib更容易:

import pandas as pd
import matplotlib.pyplot as plt

table={'time':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],
       'data':[1,1,2,2,2,1,2,3,4,5,1,2,2,2,3],
       'type':['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']}
df=pd.DataFrame(table, columns=['time','data','type'])

groups = df.groupby('type')

fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(group['time'], group['data'], label=name)
ax.legend(loc='best')

plt.show()

enter image description here

如果您更喜欢使用pandas绘图包装器,则需要覆盖图例标签:

import pandas as pd
import matplotlib.pyplot as plt

table={'time':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],
       'data':[1,1,2,2,2,1,2,3,4,5,1,2,2,2,3],
       'type':['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']}
df=pd.DataFrame(table, columns=['time','data','type'])

df.index = df['time']
groups = df[['data', 'type']].groupby('type')

fig, ax = plt.subplots()
groups.plot(ax=ax, legend=False)
names = [item[0] for item in groups]
ax.legend(ax.lines, names, loc='best')

plt.show()

enter image description here

答案 1 :(得分:1)

只需投入seaborn解决方案。

import seaborn as sns
import matplotlib.pyplot as plt

g = sns.FacetGrid(df, hue="type", size=5)
g.map(plt.plot, "time", "data")
g.add_legend()

enter image description here