python时间序列将个人工作日绘制为线条

时间:2018-04-11 05:23:42

标签: python matplotlib

对于时间序列,有一种简单的方法可以将每个工作日绘制为不同的线图吗?在此示例中,星期日为红色,其他日期为黄色点。有没有办法用线条加入所有红点 - 并且在一周中的其他日子也这样做。 例如:

import pandas as pd
import matplotlib.pyplot as plt
ts = pd.DataFrame(pd.Series(np.random.randn(100), index=pd.date_range('1/1/2000', periods=100)))
ts.columns = ['quantity']
ts['weekday'] = ts.index.weekday_name
colors = dict(zip(ts.weekday.unique(), ['yellow', 'yellow', 'yellow', 'yellow', 'yellow', 'yellow', 'red']))
plt.scatter(x = ts.index, y = ts.quantity, color=ts.weekday.map(lambda x: colors[x]))
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

一种方法是按每个组的weekdayapply线图对数据框进行分组。希望这是你想要的:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

ts = pd.DataFrame(np.random.randn(100),
                  index=pd.date_range('1/1/2000', periods=100),
                  columns=['quantity'])
ts['weekday'] = ts.index.weekday_name
fig, ax = plt.subplots()
ts.groupby('weekday').agg(lambda x: x['quantity'].plot(ax=ax,
                                                       legend=True,
                                                       label=x['weekday'][0]))
plt.show()

enter image description here

编辑:从周一到周日对工作日进行排序

这里的关键更改是使用weekday而不是weekday_name,因为Pandas将其编码为" Monday = 0,Sunday = 6"。然后,您需要在绘图期间使用weekday_name标记它们:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

ts = pd.DataFrame(np.random.randn(100),
                  index=pd.date_range('1/1/2000', periods=100),
                  columns=['quantity'])
ts['weekday'] = ts.index.weekday
fig, ax = plt.subplots()
ts.groupby('weekday').agg(lambda x: x['quantity'].plot(ax=ax,
                                                       legend=True,
                                                       label=x.index.weekday_name[0]))
plt.show()

enter image description here