首页 > 解决方案 > Python:使用 matplotlib 的时间序列类可视化

问题描述

我有一个带有时间序列预测类的数组,格式为:

[[DateTime, "Class1"], [DateTime, "Class2"] .... ] 

我想在一个绘图中显示原始时间序列数据,下面有一个颜色条,表示每个时间间隔的预测类,这里可以看到这个颜色条的一个例子(这里的x轴应该是日期时间格式) .

我通过为每个[DateTime, "Class1"]-pair 附加像素来实现该示例。但是,问题在于每个连续的 DateTime 之间的间隔是不同的。因此,每个“像素”不应具有相同的宽度。

我的下一个想法是使用行集合,使用具有适当颜色的水平线连接每个 DateTime:

def plot_prediction_colorbar(self, ax): 
        classes = self.df["Prediction"].unique() #get all classes
        colors = cm.rainbow(np.linspace(0,1,len(classes))) #color for each one

        dt_pred_arr = self.df[["DateTime", "Prediction"]].to_numpy()

        color_arr = []
        line_arr = [] 
        last_coord = None
        last_color = None

        for idx, (dt, pred) in enumerate(dt_pred_arr): 
            dt = date2num(dt)
            cur_coord = [dt,0] 
            if last_coord is not None and last_color is not None:
                color_arr.append(last_color)
                line_arr.append([ last_coord , cur_coord])

            last_coord = cur_coord
            if pred in classes: #For predicted classes
                last_color = colors[np.where(classes==pred)[0]][0]
                
        linecoll = LineCollection(line_arr, colors=color_arr)
        ax.add_collection(linecoll)

line_array但是,没有显示任何行......运行时条目 的一个示例是:[[18550.766805555555, 0], [18550.766793981482, 0]] 这可能是由于日期时间转换导致高浮点数几乎没有差异吗?

任何帮助将不胜感激!

标签: pythonmatplotlibclassification

解决方案


推荐阅读