绘制图表,显示一组列表中某个范围内的哪些值

2024-06-08 18:00:12 发布

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

我有一个由金融股票ID[01400]和时间戳[01800]组成的数据集。对于给定的ID,它有或没有给定时间戳的数据

我创建了一个字典,其中每个键都是一个ID,每个值都是该ID包含数据的所有时间戳的列表

现在我想绘制一个图表,每一行对应一个ID,每一列对应一个时间戳。如果ID i具有时间戳jif j in dict[i])的数据,则图表的每个单元格[i, j]将变为绿色,否则变为红色

以下是我在Excel中手动生成的示例:

enter image description here

这可以通过matplotlip或其他库完成吗

由于图表的大小为1400x1800,因此单元格可能非常小。我正试图对数据进行重新排序,以使相邻ID之间相交的绿色单元格数量最大化,因此此图表将使我能够可视化我在数据集上实现这些重叠/相交的情况

为了提供一些数据,我只需遍历字典中的前20个ID,并打印出ID及其时间戳列表each line is in the form of ^{}

编辑:

这是我第一次尝试小规模的数据示例。虽然,这确实实现了我开始要做的,但这是一个非常暴力的解决方案,因此任何关于改进的建议都将不胜感激

import matplotlib.pyplot as plt
import pandas as pd

TSs = [0, 1, 2, 3, 4, 5]
ID_TS = {0: [1, 2, 3], 1: [2, 3, 4, 5]}

df = pd.DataFrame(index=ID_TS.keys(), columns=TSs)

for ID, TS in ID_TS.items():
    bools = []
    for i in TSs:
        if i in TS:
            bools.append(True)
        else:
            bools.append(False)
    df.loc[ID] = bools

plt.imshow(df, cmap='hot', interpolation='nearest')
plt.show()

Tags: 数据inid示例df列表if字典
1条回答
网友
1楼 · 发布于 2024-06-08 18:00:12

生成数据帧的代码不起作用。所以我有点放肆

import numpy
import pandas
from matplotlib import pyplot
from matplotlib import ticker

TSs = [0, 1, 2, 3, 4, 5]
ID_TS = {0: [1, 2, 3, numpy.nan], 1: [2, 3, 4, 5]}

fig, ax = pyplot.subplots()

img = ( 
    pandas.DataFrame(data=ID_TS, columns=TSs)
        .isnull()
        .pipe(numpy.bitwise_not)
        .pipe(ax.pcolor, cmap='RdYlGn', edgecolors='k')
)

unit_ints = ticker.MultipleLocator(1)

ax.set_xlabel('Time')
ax.set_ylabel('ID')
ax.yaxis.set_major_locator(unit_ints)
ax.xaxis.set_major_locator(unit_ints)

enter image description here

相关问题 更多 >