为df.plot.bar绘制垂直线是可行的,但对于线型图则不行

2024-09-28 21:31:31 发布

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

我在这里按照我的问题的全部步骤:Pandas Dataframe : How to add a vertical line with label to a bar plot when your data is time-series?

它本应该可以解决我的问题,但当我将绘图类型更改为直线时,垂直线没有出现。我复制相同的代码,并将绘图类型更改为“线”而不是“条形”:

如您所见,垂直线(红色)出现

# function to plot a bar 
def dessine_line3(madataframe,debut_date , mes_colonnes):

madataframe.index = pd.to_datetime(madataframe.index,format='%m/%d/%y')
df = madataframe.loc[debut_date:,mes_colonnes].copy()
filt = (df[df.index == '4/20/20']).index
df.index.searchsorted(value=filt)
fig,ax = plt.subplots()
df.plot.bar(figsize=(17,8),grid=True,ax=ax)
ax.axvline(df.index.searchsorted(filt), color="red", linestyle="--", lw=2, label="lancement")
plt.tight_layout()

输出:enter image description here

但是我只是通过改变绘图类型来改变代码:没有垂直线,x轴(日期)也改变了enter image description here

所以我写了另一个代码,就是用垂直线画线

ax = madagascar_maurice_case_df[["Madagascar Covid-19 Ratio","Maurice Covid-19 Ratio"]].loc['3/17/20':].plot.line(figsize=(17,7),grid=True)

filt=(df[df.index='4/20/20'])。index ax.axvline(df.index.searchsorted(filt),color=“red”,linestyle=“--”,lw=2,label=“lancement”) plt.show()

但结果是一样的

以下是我的最终代码:

def dessine_line5(madataframe,debut_date , mes_colonnes):
    plt.figure(figsize=(17,8))
    plt.grid(b=True,which='major',axis='y')
    df = madataframe.loc[debut_date:,mes_colonnes]
    sns.lineplot(data=df)
    lt = datetime.toordinal(pd.to_datetime('4/20/20'))
    plt.axvline(lt,color="red",linestyle="--",lw=2,label="lancement")
    plt.show()

结果是: enter image description here


Tags: to代码dfdateindexplotpltax
1条回答
网友
1楼 · 发布于 2024-09-28 21:31:31

绘图勾号locs

  • 问题在于,根据打印类型和api,打印记号位置的样式不同
    • df.plotplt.plotsns.lineplot
  • ticks, labels = plt.xticks()放在df.plot.bar(figsize=(17,8),grid=True,ax=ax)之后,打印ticks将得到array([0, 1, 2,..., len(df.index)]),这就是df.index.searchsorted(filt)工作的原因,它会产生一个整数位置
  • df.plot()对于我的样本日期范围,有像array([13136, 13152, 13174, 13175], dtype=int64)这样的勾选LOC。我不知道这些数字是如何推导出来的,所以我不知道如何将日期转换成那种格式
  • sns.lineplotplt.plot有tick loc,它们是日期时间的顺序表示,array([737553., 737560., 737567., 737577., 737584., 737591., 737598., 737607.]

对于带有示例的lineplot,请执行以下操作:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime

sns.lineplot(data=df)
lt = datetime.toordinal(pd.to_datetime('2020/04/20'))
plt.axvline(lt, color="red", linestyle=" ", lw=2, label="lancement")
plt.show()

对于我的示例数据:

import numpy as np

data = {'a': [np.random.randint(10) for _ in range(40)],
        'b': [np.random.randint(10) for _ in range(40)],
        'date': pd.bdate_range(datetime.today(), periods=40).tolist()}

df = pd.DataFrame(data)
df.set_index('date', inplace=True)

sns.lineplot(data=df)
ticks, labels = plt.xticks()
lt = datetime.toordinal(pd.to_datetime('2020-05-19'))
plt.axvline(lt, color="red", linestyle=" ", lw=2, label="lancement")
plt.show()

enter image description here

相关问题 更多 >