首页 文章

绘制基于Python条件的多彩时间序列图[重复]

提问于
浏览
1

这个问题在这里已有答案:

我有一个pandas Financial timeseries DataFrame,有两列和一个日期时间索引 .

TOTAL.PAPRPNT.M  Label
1973-03-01        25504.000      3
1973-04-01        25662.000      3
1973-05-01        25763.000      0
1973-06-01        25996.000      0
1973-07-01        26023.000      1
1973-08-01        26005.000      1
1973-09-01        26037.000      2
1973-10-01        26124.000      2
1973-11-01        26193.000      3
1973-12-01        26383.000      3

如您所见,每个数据集对应一个'Label' . 如果从前一个'point'到下一个'point'的行具有某些特征(不同类型的库存图更改),则此标签应基本分类,因此对每个图使用 separate color . 这个问题与这个问题有关Plot Multicolored line based on conditional in python但'groupby'部分完全忽略了我的理解,这个方案是Bicolored方案而不是多彩的方案(我有四个标签) .

我想根据与数据框中每个条目相关联的标签创建图形的多色图 .

1 回答

  • 0

    这是我认为您尝试做的一个例子 . 它基于评论中提到的MPL文档,并使用随机生成的数据 . 只需将色彩映射边界映射到由类数给出的离散值 .

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from matplotlib.colors import ListedColormap, BoundaryNorm
    import pandas as pd
    
    
    num_classes = 4
    ts = range(10)
    df = pd.DataFrame(data={'TOTAL': np.random.rand(len(ts)), 'Label': np.random.randint(0, num_classes, len(ts))}, index=ts)
    print(df)
    
    cmap = ListedColormap(['r', 'g', 'b', 'y'])
    norm = BoundaryNorm(range(num_classes+1), cmap.N)
    points = np.array([df.index, df['TOTAL']]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    
    lc = LineCollection(segments, cmap=cmap, norm=norm)
    lc.set_array(df['Label'])
    
    fig1 = plt.figure()
    plt.gca().add_collection(lc)
    plt.xlim(df.index.min(), df.index.max())
    plt.ylim(-1.1, 1.1)
    plt.show()
    

    每个线段都根据 df['Label'] 中给出的类标签着色 . 这是一个示例结果:

相关问题