gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:34 25 4
gpt4 key购买 nike

我有一个 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

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

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

最佳答案

这是我认为您尝试做的一个示例。它基于评论中提到的 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'] 中给出的类标签着色,这是一个示例结果:

enter image description here

关于python - 在Python中基于条件绘制多色时间序列图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48393080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com