首页 > 解决方案 > 如何根据 matplotlib 中的单元格字符串以彩色网格方式绘制时间序列?

问题描述

我正在尝试 在 matplotlib中生成像这样的

基于这样构造的 pandas 数据框:

   2020-01-01  2020-01-02  2020-01-03  ...
X    yellow        red         red     ...
Y    orange       orange       red     ...
Z     red         yellow     yellow    ...
...   ...          ...         ...     ...

我认为这可能是用 2D 直方图完成的,但没有运气。我已经看到这pcolor可能是我正在寻找的功能,但我无法管理它与我的时间系列数据框一起工作。

标签: pythonpandasmatplotlib

解决方案


你可以用seaborn. 您需要用数字替换颜色,因此您将拥有这样的数据框:

数据框

你可以sns.heatmap用来绘制:

热图

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

data = {'date': pd.date_range("2020-01-01", "2020-01-31", freq="1D").strftime('%d %b'),
        'a': np.random.randint(3, size=31), 'b': np.random.randint(3, size=31),
        'c': np.random.randint(3, size=31), 'd': np.random.randint(3, size=31),
        'e': np.random.randint(3, size=31), 'f': np.random.randint(3, size=31)}
df = pd.DataFrame.from_dict(data)
df = df.set_index('date')
df = df.transpose()

fig, ax = plt.subplots(figsize=[10,2])
ax = sns.heatmap(df, cmap=['yellow', 'orange', 'red'], cbar=False)

如果您愿意matplotlib,可以使用imshow

显示

from matplotlib.colors import ListedColormap

fig, ax = plt.subplots(figsize=[10,2])
ax.set_xticks(np.arange(len(df.columns)))
ax.set_yticks(np.arange(len(df.index)))
ax.set_xticklabels(df.columns)
ax.set_yticklabels(df.index)
plt.setp(ax.get_xticklabels(), rotation=90)
ax.imshow(df, ListedColormap(['yellow', 'orange', 'red']))

推荐阅读