如何在时间序列数据中标记类别? - python

我有时间序列数据,其中时间序列上的每个点也是类别的一部分。共有3个类别,通常彼此之间的几个点位于同一类别中。我希望能够绘制时间序列,但是要根据观察结果所在的类别来更改线条的颜色。

我目前有一个解决方案,其中包含时间序列,然后根据观察结果的类别为每个观察值着色点,但是看起来很混乱。

我还尝试了将类别分为3个数据集并分别进行绘制,但是当类别在系列中更改时,线条不会连接

我目前正在使用python,但是由于有了数据集,因此我不仅限于python解决方案。

数据快照:

Date         Value      Group
2016-04-01   0.65       2 
2016-04-02   0.66       0 
2016-04-03   0.65       0 
2016-04-04   0.69       1 

参考方案

这应该是您想要的,我也使用熊猫:

import pandas as pd
import matplotlib.pyplot as mpl

df = pd.read_csv("data.txt", sep='\s+') #or however you build the dataframe with pandas

for i in range(len(df.index)):
    if df.loc[i,'Group'] == 0:
        col = 'g' #green
    elif df.loc[i,'Group'] == 1:
        col = 'r' #red
    elif df.loc[i,'Group'] == 2:
        col = 'c' #cyan
    subdf = df.loc[i:i+2] #selecting two points
    mpl.plot(subdf['Date'], subdf['Value'], 'o'+col) #plot bullet points
    mpl.plot(subdf['Date'], subdf['Value'], col) #plot connecting line

mpl.show()

结果如下:

如何在时间序列数据中标记类别? - python

这个想法是将每对都循环遍历系列,并绘制两次,前者绘制项目符号点,后者绘制连接段。从组中选择颜色(here颜色列表)。
我添加了项目符号点以显示最后一点的不同颜色:它可能属于不同的组。段的颜色对应于与第一点的组关联的颜色。

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Matplotlib'粗体'字体 - python

跟随this example:import numpy as np import matplotlib.pyplot as plt fig = plt.figure() for i, label in enumerate(('A', 'B', 'C', 'D')): ax = f…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…