Python中基于条件的彩色时序图绘制

2024-09-30 10:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

pandas有两个带有时间框架的date和timeseries列。在

            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”部分完全忽略了我的理解,这个方案是双色方案,而不是多色方案(我有四个标签)。在

我想根据与dataframe中每个条目相关联的标签创建一个多色图。在


Tags: 数据框架类型pandasdate时间方案特征
1条回答
网友
1楼 · 发布于 2024-09-30 10:34:17

这是一个我认为你想做什么的例子。它基于评论中提到的MPL文档,使用随机生成的数据。 只需将colormap边界映射到由类数给定的离散值。在

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

相关问题 更多 >

    热门问题