从数据框中绘制多个时间序列

问题描述

我想用Y轴表示销售额,用X轴表示时间。每种车型一条线。我设法为总销售量画了一条线。有没有建议为每种汽车型号排队?

cars = {"Date" : ["2020-01-29","2020-01-02","2020-01-24","2020-05-21","2020-12-31","2020-12-01","2020-12-01"],"Brand": ["Honda Civic","Toyota Corolla","Honda Civic","Ford Focus","Audi A4","Ford Focus"],"Price": [22000,25000,22000,27000,35000,27000]
    }
df2 = pd.DataFrame(cars,columns = ["Date","Brand","Price"])
df2["Date"] =  pd.to_datetime(df2["Date"])
df2=df2.sort_values(by="Date")
df2.index = df2["Date"]
gb2=df2.groupby([df2.index.year.values,df2.index.month.values,df2.index.day.values]).sum()
gb2.plot.line()
plt.show()

解决方法

您可以通过以下方法为每种车型绘制一条线。请注意,使用marker是因为隔离的行不会显示Toyota Corolla或Audi A4的任何绘图数据,而每个绘图数据仅由一个数据点表示。

fig,ax = plt.subplots()
for (i,b) in df2.groupby('Brand'):
    b.plot(x='Date',y='Price',marker='o',ax=ax,label=i)
ax.legend()

enter image description here