- 如何
vlines
在熊猫系列图中绘制垂直线()? - 我正在使用Pandas绘制滚动装置等,并想用垂直线标记重要位置。
- 是否可以使用
vlines
或类似的方法来完成此任务? - 在这种情况下,x轴为
datetime
。
Answers:
如果您有时间轴,并且已将熊猫作为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='-')
xposition = [pd.to_datetime('01/04/2016'), pd.to_datetime('02/04/2016'),pd.to_datetime('03/04/2016')]
然后for xc in xposition: ax.axvline(x=xc, color='k', linestyle='-')
。我得到了:ValueError: ordinal must be >= 1.
。怎么了?
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
pandas.to_datetime
转换列datetime
D型。ymin
&ymax
指定为特定的y值,而不是ylim
axes
类似的内容fig, axes = plt.subplots()
,则更plt.xlines
改为axes.xlines
plt.plot()
和 sns.lineplot()
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns # if using seaborn
plt.style.use('seaborn') # these plots use this style
# 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))
# plot
plt.plot('v', data=df, color='magenta')
y_min = df.v.min()
y_max = df.v.max()
plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x=datetime(2021, 9, 14), ymin=4, ymax=9, colors='green', ls=':', lw=2, label='vline_single')
plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
plt.show()
df.plot()
df.plot(color='magenta')
ticks, _ = plt.xticks()
print(f'Date format is pandas api format: {ticks}')
y_min = df.v.min()
y_max = df.v.max()
plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x='2020-12-25', ymin=y_min, ymax=8, colors='green', ls=':', lw=2, label='vline_single')
plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
plt.show()
import matplotlib as mpl
print(mpl.__version__)
print(sns.__version__)
print(pd.__version__)
[out]:
3.3.1
0.10.1
1.1.0
plt.style.use('seaborn')