我有一个像这样的MultiIndex数据框
Freights Passengers
Station Hogwarts Hogwarts
Direction Northbound Southbound Northbound Southbound
Date
2020-04-10 0 1 0 9
2020-04-11 0 2 0 8
2020-04-12 5 3 15 17
2020-04-13 6 4 4 26
我想获得一个带有每列曲线的图,Freights
列应为红色,而Passengers
列应为蓝色。
我设法按照下面的代码片段获得了结果,但是我想知道是否还有一种更惯用的方式(例如,避免for循环)。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Date': ['2020-04-10', '2020-04-11', '2020-04-12', '2020-04-13','2020-04-10', '2020-04-11', '2020-04-12', '2020-04-13'],
'Station': ['Hogwarts', 'Hogwarts', 'Hogwarts', 'Hogwarts','Hogwarts', 'Hogwarts', 'Hogwarts', 'Hogwarts'],
'Direction': ['Southbound', 'Southbound', 'Southbound', 'Southbound','Northbound','Northbound','Northbound','Northbound'],
'Daily trains': [10,10,20,30,0,0,20,10],
'Freights': [1,2,3,4,0,0,5,6],
'Passengers': [9,8,17,26,0,0,15,4]})
df['Date'] = pd.to_datetime(df['Date'],format="%Y-%m-%d")
df1 = df.pivot_table(index='Date', columns=['Station','Direction'],values=['Freights','Passengers'])
colors = {'Freights':'red','Passengers':'blue'}
fig, ax = plt.subplots(1)
for i in df1:
df1[i].plot(ax=ax,color=colors[i[0]])
ax.figure.savefig('so.png',bbox_inches='tight')