如何在 Python 中绘制时间序列数据?
How do I plot timeseries data in Python?
我处理大量时间序列数据,希望有一种方法可以简单地按季节绘制它;
例如;
A B C D E F G H I
01/01/2008 4 4 43 4 3 4 3 4 3
02/01/2008 43 3 4 3 34 3 4 3
03/01/2008 11 2 3 4 3 4 3 44 3
.
.
.
07/08/2021 43 3 4 3 34 3 4 3
08/09/2021 43 3 4 3 34 3 4 3
是否有一种有效的或 python-y 方法来绘制此图,使其类似于季节性图表但以每日为粒度?
可能类似于以下内容?
理想情况下,这也可以创建一个数据框,其中包含每年的数据列,索引为 dd/mm 日期格式也可以使用。
非常感谢任何帮助!
对于绘图,我建议你看一下 matplotlib。对于数据框,您可以使用 pandas
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame(yourdata) #to create a dataframe
df.plot() #to plot your data or df.plot(x="A",y="Date") to select what to plot
df["NewDate"] = pd.to_datetime(df['Date'], format='%d/%m') #to create the the date column with format dd/mm (based on the date column you already have)
- 简单 plotly
- 已经用随机数据模拟了你的数据
- 关键步骤是一个 x 轴,它在多年的季节性中保持不变。已使用 2021 年的日期使用年中的某天生成 2021 年的日期。第二步是设置日期格式,因为年份是无关紧要的
- 我的数据显然没有季节性,因为它是随机的...
import numpy as np
import pandas as pd
import plotly.express as px
n = 365 * 14
df = pd.DataFrame(
index=pd.date_range("1-jan-2008", periods=n),
data={c: np.random.randint(1, 45, n) for c in list("ABCDEFGHI")},
)
fig = px.line(
df.assign(
year=df.index.year,
doy=pd.to_datetime(df.index.day_of_year.values + (2021 * 1000), format="%Y%j"),
value=df.mean(axis=1),
),
x="doy",
y="value",
color="year",
template="plotly_dark"
)
# just for demo purposes, make some traces invisible
for t in fig.data:
if int(t["name"])<2016: t["visible"]="legendonly"
fig.update_layout(xaxis={"tickformat":"%d-%b"})
请注意,监视季节性 时间序列数据不同于绘制时间序列数据。随着时间的推移,需要将数据分解成它的组件。您可以使用 plt.style.use('dark_background')
在深色背景中检查此 . However, just to plot time-series data regardless of format of timestamps,它可能如下所示:
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('dark_background')
colors = [
'#08F7FE', # teal/cyan
'#FE53BB', # pink
'#F5D300', # yellow
'#00ff41' # matrix green
]
df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1],
'B': [4, 5, 5, 7, 9, 8, 6],
'C': [7, 5, 3, 1, 5, 9, 3],
'D': [3, 6, 7, 4, 3, 2, 1],
'date':['10-10-2016', '10-10-2017', '10-10-2018', '10-10-2019', '10-10-2020', '10-10-2021', '10-10-2022']})
# make sure the time column is actually time format
df['date']=pd.to_datetime(df['date'])
# set time as the index
df.set_index('date',inplace=True)
fig, ax = plt.subplots()
df.plot(marker='o', color=colors, ax=ax)
ax.figure.autofmt_xdate(rotation=45, ha='center')
plt.legend(loc='best')
plt.show()
如果你想把它做得更花哨,可以关注Time series Visualization or Matplotlib Cyberpunk Style
为了解决以下问题:
Ideally this may also create a dataframe with yearly columns of data with the index being dd/mm date format to also use.
基于此 ,一旦将日期索引传递给 x 轴,您就可以使用具有所需日期格式的 import matplotlib.dates as md
:
df.plot(marker='o', color=colors, ax=ax)
ax.set_xticks(df.index)
ax.figure.autofmt_xdate(rotation=45, ha='center')
####### Use the below functions #######
import matplotlib.dates as md
dtFmt = md.DateFormatter('%d-%b') # define the formatting
ax.xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.legend(loc='best')
plt.show()
我处理大量时间序列数据,希望有一种方法可以简单地按季节绘制它;
例如;
A B C D E F G H I
01/01/2008 4 4 43 4 3 4 3 4 3
02/01/2008 43 3 4 3 34 3 4 3
03/01/2008 11 2 3 4 3 4 3 44 3
.
.
.
07/08/2021 43 3 4 3 34 3 4 3
08/09/2021 43 3 4 3 34 3 4 3
是否有一种有效的或 python-y 方法来绘制此图,使其类似于季节性图表但以每日为粒度?
可能类似于以下内容?
理想情况下,这也可以创建一个数据框,其中包含每年的数据列,索引为 dd/mm 日期格式也可以使用。
非常感谢任何帮助!
对于绘图,我建议你看一下 matplotlib。对于数据框,您可以使用 pandas
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame(yourdata) #to create a dataframe
df.plot() #to plot your data or df.plot(x="A",y="Date") to select what to plot
df["NewDate"] = pd.to_datetime(df['Date'], format='%d/%m') #to create the the date column with format dd/mm (based on the date column you already have)
- 简单 plotly
- 已经用随机数据模拟了你的数据
- 关键步骤是一个 x 轴,它在多年的季节性中保持不变。已使用 2021 年的日期使用年中的某天生成 2021 年的日期。第二步是设置日期格式,因为年份是无关紧要的
- 我的数据显然没有季节性,因为它是随机的...
import numpy as np
import pandas as pd
import plotly.express as px
n = 365 * 14
df = pd.DataFrame(
index=pd.date_range("1-jan-2008", periods=n),
data={c: np.random.randint(1, 45, n) for c in list("ABCDEFGHI")},
)
fig = px.line(
df.assign(
year=df.index.year,
doy=pd.to_datetime(df.index.day_of_year.values + (2021 * 1000), format="%Y%j"),
value=df.mean(axis=1),
),
x="doy",
y="value",
color="year",
template="plotly_dark"
)
# just for demo purposes, make some traces invisible
for t in fig.data:
if int(t["name"])<2016: t["visible"]="legendonly"
fig.update_layout(xaxis={"tickformat":"%d-%b"})
请注意,监视季节性 时间序列数据不同于绘制时间序列数据。随着时间的推移,需要将数据分解成它的组件。您可以使用 plt.style.use('dark_background')
在深色背景中检查此
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('dark_background')
colors = [
'#08F7FE', # teal/cyan
'#FE53BB', # pink
'#F5D300', # yellow
'#00ff41' # matrix green
]
df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1],
'B': [4, 5, 5, 7, 9, 8, 6],
'C': [7, 5, 3, 1, 5, 9, 3],
'D': [3, 6, 7, 4, 3, 2, 1],
'date':['10-10-2016', '10-10-2017', '10-10-2018', '10-10-2019', '10-10-2020', '10-10-2021', '10-10-2022']})
# make sure the time column is actually time format
df['date']=pd.to_datetime(df['date'])
# set time as the index
df.set_index('date',inplace=True)
fig, ax = plt.subplots()
df.plot(marker='o', color=colors, ax=ax)
ax.figure.autofmt_xdate(rotation=45, ha='center')
plt.legend(loc='best')
plt.show()
如果你想把它做得更花哨,可以关注Time series Visualization or Matplotlib Cyberpunk Style
为了解决以下问题:
Ideally this may also create a dataframe with yearly columns of data with the index being dd/mm date format to also use.
基于此 import matplotlib.dates as md
:
df.plot(marker='o', color=colors, ax=ax)
ax.set_xticks(df.index)
ax.figure.autofmt_xdate(rotation=45, ha='center')
####### Use the below functions #######
import matplotlib.dates as md
dtFmt = md.DateFormatter('%d-%b') # define the formatting
ax.xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.legend(loc='best')
plt.show()