使用matplotlib为时间序列标记图形中的点

2024-06-17 18:15:58 发布

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

我有一个有3列的熊猫数据帧。 我在Y轴上绘制col1,在X轴上绘制时间戳系列。 对于本系列,每当col2为-1时,我想在图中突出显示异常点。我试着用ax.文本但是我不能得到正确的坐标,因为X轴是一个时间序列。在下面的例子中,我试图绘制第三行坐标,因为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()

示例数据看起来像

^{pr2}$

Tags: 数据textimportdfgettime时间绘制
1条回答
网友
1楼 · 发布于 2024-06-17 18:15:58

我发现我可以把它转换成秒,然后把这些点标记为异常。我就是这么做的。在

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

相关问题 更多 >