简体   繁体   English

使用matplotlib标注时间图中的点

[英]label a point in graph using matplotlib for timeseries

I have a pandas dataframe with 3 columns. 我有3列的pandas数据框。 I plot col1 on Y axis and a time_stamps series on X axis. 我在Y轴上绘制col1,在X轴上绘制time_stamps系列。 For this series whenever col2 is -1, I want to highlight that point on graph as anomaly. 对于此系列,每当col2为-1时,我都希望在图形上突出显示该点为异常。 I tried to get the coordinate and highlight using ax.text but I cannot get the correct coordinate since X axis is a time series. 我尝试使用ax.text获取坐标并突出显示,但由于X轴是时间序列,因此无法获取正确的坐标。 In the example below I am trying to plot third row coordinates since col2[2]==-1. 在下面的示例中,由于col2 [2] ==-1,我试图绘制第三行坐标。

import pandas
import matplotlib.pyplot as plt
df=df[["time_stamps","col1"]]
df.set_index("time_stamps",inplace=True)
ax=df.plot()
ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()]
new_labels=[tick[-6:] for tick in ticklabels]
ax.xaxis.set_ticklabels(new_labels)
x1="16965 days 17:52:03"
y1=0.7
ax.text(x1, y1, "anaomly", fontsize=15)
plt.show()

Sample data looks like 样本数据看起来像

time_stamp=[16965 days 17:52:00,16965 days 17:52:02
16965 days 17:52:03,16965 days 17:52:05
16965 days 17:52:06,16965 days 17:52:08
16965 days 17:52:09,16965 days 17:52:11
16965 days 17:52:12,16965 days 17:52:14]
col1=[0.02,0.01,0.7,0.019,0.019,0.017,0.023,0.04,0.072,0.05]  
col2=[1,1,-1,1,1,1,1,1,1,1] 

I figured it out that I can convert it to seconds and then label the points as anomalies. 我发现可以将其转换为秒,然后将这些点标记为异常。 This is what i did. 这就是我所做的。

def changetotimedelta(row): 
    return pd.to_timedelta(row["time_stamps"])/ np.timedelta64(1,'D') 
def main() 
 df=pd.read_csv(inputFile)    
 df["time"]=df.apply(changetotimedelta,axis=1)
 new_df=df[["time","col1"]]
 new_df.set_index("time",inplace=True)
 ax=new_df.plot()
 x1=pd.to_timedelta("16965 days 17:52:03")/ np.timedelta64(1,'D')  
 y1=0.7
 ax.annotate('anomaly', xy=(x1, y1), xytext=(x2, 1),
            arrowprops=dict(facecolor='red', shrink=0.01),)

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM