在Python中基于条件绘制多色时间序列图

Dan*_*lvi 1 python plot time-series matplotlib pandas

我有一个 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
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,每个数据集对应一个“标签”。如果从前一个“点”到下一个“点”的线具有某些特征(不同类型的股票图表变化),则该标签本质上应该进行分类,因此为每个图使用单独的颜色。这个问题与这个问题相关Plot Multicolored line based on conditional in python但“groupby”部分完全跳过了我的理解,这个方案是双色方案而不是多色方案(我有四个标签)。

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

小智 7

这是我认为你试图做的一个例子。它基于评论中提到的 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()
Run Code Online (Sandbox Code Playgroud)

每个线段根据df['Label']以下示例结果中给出的类标签进行着色:

在此输入图像描述