如何在一个图形中绘制多个折线图(覆盖/分组) [英] How to plot several line charts in one figure (overlay/groupby)
问题描述
我想说明我的数据中几个人的一个变量随时间的变化.我在这里遇到一些基本命令的问题.
I would like to illustrate the change in one variable for several persons in my data over time. I have several issues with basic commands here.
这是我的数据:
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
我尝试使用matplotlib
并开始为我的每个唯一ID循环.我是这个包的新手.首先,如何为每个图指定一条线仅连接3个点,而不是全部?其次,如何将这些图叠加到一个图中?
I tried to make use of matplotlib
and started to loop for each of my unique IDs. I'm new to this package. First, how can I specify for each plot that only 3 points are connected for a line, not all? Second, how can I overlay those plots in one figure?
import matplotlib.pyplot as plt
for i in df.id.unique():
df.plot.line(x='year', y='money')
推荐答案
由于已标记matplotlib
,因此一种解决方案是在循环遍历DataFrame之前检查id
,然后使用df[df['id']==i]
进行绘制.
Since you have tagged matplotlib
, one solution is to check for the id
while looping through the DataFrame before plotting using df[df['id']==i]
.
要在一个图形中叠加这些图,请创建一个图形对象,并将轴ax
传递给df.plot()
函数.
To overlay those plots in one figure, create a figure object and pass the axis ax
to the df.plot()
function.
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)
Pandas解决方案如下所示.在这里,您以后必须修改图例.
Pandas solution using groupby
would look like following. Here you will have to modify the legends later.
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)
这篇关于如何在一个图形中绘制多个折线图(覆盖/分组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!