【问题标题】:Plotting a vertical line for df.plot.bar works, but it doesn't for a lineplot为 df.plot.bar 绘制垂直线有效,但不适用于线图
【发布时间】:2020-05-08 16:55:30
【问题描述】:

我在这里遵循了我的问题的所有步骤:Pandas Dataframe : How to add a vertical line with label to a bar plot when your data is time-series?

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

你可以看到 bar ,垂直线(红色)出现。

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

输出:

但是我只是通过将绘图类型更改为 line 来更改代码:没有垂直线,x 轴(日期)也发生了变化。

所以我写了另一个代码来用垂直线画线

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

结果是:

【问题讨论】:

  • 请提供完整的mcve

标签: python pandas dataframe matplotlib


【解决方案1】:

绘图刻度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) 的刻度位置。我实际上并不知道这些数字是如何得出的,所以我不知道如何将日期转换为那种格式。
  • sns.lineplotplt.plot 的刻度位置是日期时间的序数表示,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()

【讨论】:

  • 非常感谢您的帮助。我真的很感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 2015-01-22
相关资源
最近更新 更多