G.David
G.David

Reputation: 55

Python heatmap with unequal block sizes

I have the following dataset:

results=[array([6.06674849e-18, 2.28597646e-03]), array([0.02039694, 0.01245901, 0.01264321, 0.00963068]), array([2.28719585e-18, 5.14800709e-02, 2.90957713e-02, 0.00000000e+00,
       4.22761202e-19, 3.21765246e-02, 8.86959187e-03, 0.00000000e+00])]

I'd like to create a heatmap from it which looks similarly to the following figure: enter image description here

Is it possible to create such diagram with seaborn or matplotlib or any other plotting package, and if so, how to do this?

Upvotes: 0

Views: 1386

Answers (1)

JohanC
JohanC

Reputation: 80319

One approach is to equalize the row lengths with np.repeat. This only works well if all rows have a length that is a divisor of the longest row length.

The data suggest using a LogNorm, although such a norm gets distracted with the zeros in the sample input.

Some code to illustrate the idea:

from matplotlib import pyplot as plt
from matplotlib import colors as mcolors
import numpy as np

results = [np.array([6.06674849e-18, 2.28597646e-03]),
           np.array([0.02039694, 0.01245901, 0.01264321, 0.00963068]),
           np.array([2.28719585e-18, 5.14800709e-02, 2.90957713e-02, 0.00000000e+00,
                     4.22761202e-19, 3.21765246e-02, 8.86959187e-03, 0.00000000e+00])]
longest = max([len(row) for row in results])
equalized = np.array( [np.repeat(row, longest // len(row)) for row in results])
# equalized = np.where(equalized == 0, np.NaN, equalized)
norm = mcolors.LogNorm()
heatmap = plt.imshow(equalized, cmap='nipy_spectral', norm=norm, interpolation='nearest',
                     origin='lower', extent=[0, 6000, 0.5, len(results)+0.5])
plt.colorbar(heatmap)
plt.gca().set_aspect('auto')
plt.yticks(range(1, len(results) + 1))
plt.show()

enter image description here

Another example with 7 levels (random numbers). Input generated as:

bands = 7
results = [np.random.uniform(0, 1, 2**i) for i in range(1, bands+1)]

example with 7 levels

Upvotes: 1

Related Questions