使用 pandas TimeSeries创建热图 [英] Create heatmap using pandas TimeSeries

查看:306
本文介绍了使用 pandas TimeSeries创建热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Pandas DataFrame TimeSeries列(df_all.ts)作为X轴创建MatplotLib热图(pcolormesh)。

I need to create MatplotLib heatmap (pcolormesh) using Pandas DataFrame TimeSeries column (df_all.ts) as my X-axis.

如何将Pandas TimeSeries列转换为可以在np.meshgrid(x,y)函数中用作X轴的东西来创建热图?解决方法是使用与pandas列中相同的参数创建Matplotlib drange,但是有一个简单的方法?

How to convert Pandas TimeSeries column to something which can be used as X-axis in np.meshgrid(x, y) function to create heatmap? The workaround is to create Matplotlib drange using same parameters as in pandas column, but is there a simple way?

x = pd.date_range(df_all.ts.min(),df_all.ts.max(),freq='H')
xt = mdates.drange(df_all.ts.min(), df_all.ts.max(), dt.timedelta(hours=1))
y = arange(ylen)
X,Y = np.meshgrid(xt, y)


推荐答案

我不知道一个时间序列的热图的意思,但是对于一个数据帧,你可以这样做: p>

I do not know what you mean by heat map for a time series, but for a dataframe you may do as below:

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

from itertools import product
from string import ascii_uppercase
from matplotlib import patheffects

m, n = 4, 7 # 4 rows, 7 columns
df = pd.DataFrame(np.random.randn(m, n),
                  columns=list(ascii_uppercase[:n]),
                  index=list(ascii_uppercase[-m:]))


ax = plt.imshow(df, interpolation='nearest', cmap='Oranges').axes

_ = ax.set_xticks(np.linspace(0, n-1, n))
_ = ax.set_xticklabels(df.columns)
_ = ax.set_yticks(np.linspace(0, m-1, m))
_ = ax.set_yticklabels(df.index)

ax.grid('off')
ax.xaxis.tick_top()

可选择打印实际每个正方形中间的值,可以看到一些阴影,你可以这样做:

optionally, to print actual values in the middle of each square, with some shadows for readability, you may do:

path_effects = [patheffects.withSimplePatchShadow(shadow_rgbFace=(1,1,1))]

for i, j in product(range(m), range(n)):
    _ = ax.text(j, i, '{0:.2f}'.format(df.iloc[i, j]),
                size='medium', ha='center', va='center',
                path_effects=path_effects)

这篇关于使用 pandas TimeSeries创建热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆