如何在一个图形中绘制多个折线图(覆盖/分组)

时间:2019-06-17 13:34:16

标签: python pandas matplotlib data-visualization

我想说明我的数据中几个人的一个变量随时间的变化。我在这里有一些基本命令问题。

这是我的数据:

model.similar_by_vector((model['The'] + model['fox']+ model['jumped'] + model['over'] + model['the'] + model['lazy'] + model['dog']))

我尝试使用import pandas as pd df = pd.DataFrame({'year': ['1988', '1989', '1990', '1988', '1989', '1990', '1988', '1989', '1990'], 'id': ['1', '1', '1', '2', '2', '2', '3', '3', '3'], 'money': ['5', '7', '8', '8', '3', '3', '7', '8', '10']}).astype(int) df.info() df ,并开始为我的每个唯一ID循环。我是这个包的新手。首先,如何为每个图指定一条线仅连接3个点,而不是全部?其次,如何将这些图叠加到一个图中?

matplotlib

3 个答案:

答案 0 :(得分:2)

由于您已经标记了matplotlib,所以一种解决方案是在使用id进行绘制之前,在遍历DataFrame的同时检查df[df['id']==i]

要在一个图形中叠加这些图,请创建一个图形对象,并将轴ax传递到df.plot()函数。

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'year': ['1988', '1989', '1990', '1988', '1989', '1990', '1988', '1989', '1990'],
                   'id': ['1', '1', '1', '2', '2', '2', '3', '3', '3'],
                   'money': ['5', '7', '8', '8', '3', '3', '7', '8', '10']}).astype(int)

fig, ax = plt.subplots()

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', y='money', ax=ax, label='id = %s'%i)
plt.xticks(np.unique(df.year),rotation=45)    

enter image description here

使用groupby

Pandas解决方案如下所示。在这里,您稍后必须修改图例。

df.groupby('id').plot(x='year', y='money',legend=True, ax=ax)

h,l = ax.get_legend_handles_labels()
ax.legend(h, df.id.unique(), fontsize=12)
plt.xticks(np.unique(df.year), rotation=45)

答案 1 :(得分:2)

也可以通过简单的pivot

完成
df.pivot(index='year', columns='id', values='money').plot(rot=45)

enter image description here

如果某些条目缺少年份,则将无法完美绘制,因此请添加插值:

(df.pivot(index='year', columns='id', values='money')
   .apply(pd.Series.interpolate, limit_area='inside')
   .plot())

答案 2 :(得分:2)

您也可以使用groupby

df.set_index('year').groupby('id').money.plot()

给出:

enter image description here

或者将seabornhue一起使用

sns.lineplot(x='year',y='money', hue='id', data=df)

给出:

enter image description here