如何向timeseries数据的条形图添加垂直线

2024-10-01 15:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用熊猫,假设我们有以下数据帧:

ax = madagascar_case[["Ratio"]].loc['3/17/20':]
ax.tail()

输出: enter image description here

我想在比率值之后显示一个条形图,并添加一条与特定日期相关的垂直线,例如:“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")

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

enter image description here

为了解决这个问题,我使用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()

结果比预期的更糟

enter image description here

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

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()

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

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

enter image description here

enter image description here


Tags: 代码dfplotpltredaxloclabel
1条回答
网友
1楼 · 发布于 2024-10-01 15:40:08
  • 您可以使用给定日期的索引编号绘制垂直线,
    • 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")

enter image description here

相关问题 更多 >

    热门问题