如何向时间序列数据的 pandas 条形图添加垂直线

Jul*_*one 1 python matplotlib pandas

我使用 Pandas 并假设我们有以下 DataFrame :

ax = madagascar_case[["Ratio"]].loc['3/17/20':]
ax.tail()
Run Code Online (Sandbox Code Playgroud)

出去 : 在此输入图像描述

我想显示以下比率值的条形图,并添加与特定日期相关的垂直线,例如:“4/20/20”:

当我尝试下面的代码时:

ax = madagascar_case[["Ratio"]].loc['3/17/20':].plot.bar(figsize=(17,7), grid = True)
# to add a vertical line
ax.axvline("4/20/20",color="red",linestyle="--",lw=2 ,label="lancement")
Run Code Online (Sandbox Code Playgroud)

结果是垂直线(红色)的日期错误并且没有标签:

在此输入图像描述

因此,为了解决这个问题,我使用 matplotlib 尝试了另一个代码:

p = '4/20/20'
# Dataframe 
ax = madagascar_case[["Ratio"]].loc['3/17/20':]
# plot a histogram based on ax 
plt.hist(ax,label='ratio')
# add vertical line 
plt.axvline(p,color='g',label="lancement")

plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果比预想的还要糟糕。:

在此输入图像描述

有没有最简单的方法来解决这个问题?

RVA92 >> 我遵循了你的最后一个代码:

df  = madagascar_case.loc['3/19/20':,'Ratio'].copy()
fig,ax = plt.subplots()
# plot bars 
df.plot.bar(figsize=(17,7),grid=True,ax=ax)
ax.axvline(df.index.searchsorted('4/9/20'), color="red", linestyle="--", lw=2, label="lancement")
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)

结果是,例如,当我将日期更改为“4/9/20”时,它可以工作,但是当我将日期更改为“4/20/20”时,它不正确,我不知道为什么?

ax.axvline(df.index.searchsorted('4/20/20'), color="red", linestyle="--", lw=2, label="lancement")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

RVA*_*A92 8

  • 您可以使用给定日期的索引号来绘制垂直线,
    • df.index.searchsorted('3/20/20')返回给定日期的索引号。
# Import libraries
import pandas as pd
import matplotlib.pyplot as plt

# Create test data
madagascar_case = pd.DataFrame(data={'Ratio': [0.5, 0.7, 0.8, 0.9]}, index=['3/19/20', '3/20/20', '3/21/20', '3/22/20'])

# Choose subset of data
df = madagascar_case.loc['3/19/20':, 'Ratio'].copy()

# Set up figure
fig, ax = plt.subplots()

# Plot bars
df.plot.bar(figsize=(17, 7), grid=True, ax=ax)

# Plot vertical lines
ax.axvline(df.index.searchsorted('3/20/20'), color="red", linestyle="--", lw=2, label="lancement")
ax.axvline(df.index.searchsorted('3/22/20'), color="red", linestyle="--", lw=2, label="lancement")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述