How to plot multiple lines in one figure in Pandas

2020-07-18 05:35发布

问题:

I have a dataframe with 3 columns, like this:

df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]

how can I plot a line for A, B and C, where it shows how their weight develops through the years. So I tried this:

df.groupby("euro").plot(x="year", y="MKM")

However, I get multiple plots and that is not what I want. I want all those plots in one figure.

回答1:

Does this produce what you're looking for?

import matplotlib.pyplot as plt
fig,ax = plt.subplots()

for name in ['A','B','C']:
    ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)

ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')