gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:00:07 26 4
gpt4 key购买 nike

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

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

最佳答案

一种方法是按工作日对数据框进行分组,并为每个组应用线图。希望这就是您想要的:

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

关于python时间序列将各个工作日绘制为线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49767096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com