我想说明我的数据中几个人的一个变量随时间的变化。我在这里有一些基本命令问题。
这是我的数据:
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
答案 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)
使用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)
如果某些条目缺少年份,则将无法完美绘制,因此请添加插值:
(df.pivot(index='year', columns='id', values='money')
.apply(pd.Series.interpolate, limit_area='inside')
.plot())
答案 2 :(得分:2)