Create heatmap using pandas TimeSeries

Posted on

Question :

Create heatmap using pandas TimeSeries

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

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)
Asked By: szu

||

Answer #1:

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)

heat-map

Answered By: behzad.nouri

Leave a Reply

Your email address will not be published.