繁体   English   中英

如何在 Pandas 的时间序列图上绘制垂直线?

[英]How do you plot a vertical line on a time series plot in Pandas?

  • 如何在 Pandas 系列图中绘制垂直线 ( vlines )?
  • 我正在使用 Pandas 绘制滚动方式等,并想用垂直线标记重要位置。
  • 是否可以使用vlines或类似的东西来完成此操作?
  • 在这种情况下,x 轴是datetime
plt.axvline(x_position)

它采用标准绘图格式选项( linestlyecolor等)

(文档)

如果您有对axes对象的引用:

ax.axvline(x, color='k', linestyle='--')

如果您有时间轴,并且将 Pandas 导入为 pd,则可以使用:

ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)

对于多行:

xposition = [pd.to_datetime('2010-01-01'), pd.to_datetime('2015-12-31')]
for xc in xposition:
    ax.axvline(x=xc, color='k', linestyle='-')

DataFrame 绘图函数返回AxesSubplot对象,您可以在其上添加任意数量的行。 看看下面的代码示例:

%matplotlib inline

import pandas as pd
import numpy as np

df = pd.DataFrame(index=pd.date_range("2019-07-01", "2019-07-31"))  # for sample data only
df["y"] = np.logspace(0, 1, num=len(df))  # for sample data only

ax = df.plot()
# you can add here as many lines as you want
ax.axhline(6, color="red", linestyle="--")
ax.axvline("2019-07-24", color="red", linestyle="--")

在此处输入图像描述

matplotlib.pyplot.vlines

  • 对于时间序列,轴的日期必须是正确的日期时间对象,而不是字符串。
  • 允许单个或多个位置
  • yminymax被指定为特定的 y 值,而不是ylim的百分比
  • 如果使用fig, axes = plt.subplots()类的东西引用axes ,则将plt.xlines更改为axes.xlines
  • 另请参阅如何在给定图上绘制垂直线
  • python 3.10pandas 1.4.2matplotlib 3.5.1seaborn 0.11.2

导入和示例数据

from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns  # if using seaborn

# configure synthetic dataframe
df = pd.DataFrame(index=pd.bdate_range(datetime(2020, 6, 8), freq='1d', periods=500).tolist())
df['v'] = np.logspace(0, 1, num=len(df))

# display(df.head())
                   v
2020-06-08  1.000000
2020-06-09  1.004625
2020-06-10  1.009272
2020-06-11  1.013939
2020-06-12  1.018629

制作初始图

使用matplotlib.pyplot.plotmatplotlib.axes.Axes.plot

fig, ax = plt.subplots(figsize=(9, 6))
ax.plot('v', data=df, label='v')
ax.set(xlabel='date', ylabel='v')

使用pandas.DataFrame.plot

ax = df.plot(ylabel='v', figsize=(9, 6))

使用seaborn.lineplot

fig, ax = plt.subplots(figsize=(9, 6))
sns.lineplot(data=df, ax=ax)
ax.set(ylabel='v')

添加垂直线

  • 这应该遵循用于制作情节的 3 种方法中的任何一种
y_min = df.v.min()
y_max = df.v.max()

# add x-positions as a list of date strings
ax.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')

# add x-positions as a datetime
ax.vlines(x=datetime(2020, 12, 25), ymin=4, ymax=9, colors='green', ls=':', lw=2, label='vline_single')

ax.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
plt.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM