我在这里按照我的问题的全部步骤: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()
但是我只是通过改变绘图类型来改变代码:没有垂直线,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()
绘图勾号
locs
df.plot
对plt.plot
对sns.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.lineplot
和plt.plot
有tick loc,它们是日期时间的顺序表示,array([737553., 737560., 737567., 737577., 737584., 737591., 737598., 737607.]
对于带有示例的
lineplot
,请执行以下操作:对于我的示例数据:
相关问题 更多 >
编程相关推荐