【问题标题】:label a point in graph using matplotlib for timeseries使用 matplotlib 为时间序列标记图形中的一个点
【发布时间】:2017-01-03 14:55:47
【问题描述】:

我有一个包含 3 列的 pandas 数据框。 我在 Y 轴上绘制 col1,在 X 轴上绘制 time_stamps 系列。 对于这个系列,只要 col2 为 -1,我想在图上突出显示该点为异常。我尝试使用 ax.text 获取坐标并突出显示,但我无法获得正确的坐标,因为 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()

样本数据看起来像

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] 

【问题讨论】:

    标签: python pandas matplotlib dataframe time-series


    【解决方案1】:

    我发现我可以将其转换为秒,然后将这些点标记为异常。这就是我所做的。

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

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多