Edwin Reyes
Edwin Reyes

Reputation: 97

Divide cell of heatmap in multiple rows

i'm working with a heatmap, for each cell have 3 rows of data, and now, i want to divide each cell in 3 rows, one for each row of data,

enter image description here

that way, each row will have its own color according to the value

I was trying with the following link, but I have no success dividing into 3 rows: How to create a heatmap where each cell is divided into 4 triangles?

for that reason I go to this space in search of help to be able to make this modification, I include the code that I have modified, which belongs to the link that I mentioned before,

from matplotlib import pyplot as plt
import numpy as np

M, N = 4,4
values = np.random.uniform(9, 10, (N * 1, M * 2))

fig, ax = plt.subplots()
#ax.imshow(values, extent=[-0.5, M - 0.5, N - 0.5,-0.5], cmap='autumn_r')
ax.imshow(values, extent=[-0.5,M - 0.5, N - 0.5,-0.5], cmap='autumn_r')

ax.set_xticks(np.arange(0, 4))
ax.set_xticks(np.arange(-0.5, M), minor=True)
ax.set_yticks(np.arange(0, 4))
ax.set_yticks(np.arange(-0.5, N), minor=True)
ax.grid(which='minor', lw=6, color='w', clip_on=True)
ax.grid(which='major', lw=2, color='w', clip_on=True)
ax.tick_params(length=0)
for s in ax.spines:
    ax.spines[s].set_visible(True)
plt.show()

I appreciate all the help, regards!

Upvotes: 0

Views: 684

Answers (1)

JohanC
JohanC

Reputation: 80319

When dividing the cells into 2, major tick positions can be used both to set the labels and position subdivision lines. To divide into 3 or more, it probably is easier to explicitly draw horizontal and vertical lines.

Here is some example code:

from matplotlib import pyplot as plt
import numpy as np

M, N = 4, 4  # M columns and N rows of large cells
K, L = 1, 3  # K columns and L rows to subdivide each of the cells
values = np.random.uniform(9, 10, (N * L, M * K))

fig, ax = plt.subplots()
ax.imshow(values, extent=[-0.5, M - 0.5, N - 0.5, -0.5], cmap='autumn_r')

# positions for the labels
ax.set_xticks(np.arange(0, M))
ax.set_yticks(np.arange(0, N))

# thin lines between the sub cells
for i in range(M):
    for j in range(1, K):
        ax.axvline(i - 0.5 + j / K, color='white', lw=2)
for i in range(N):
    for j in range(1, L):
        ax.axhline(i - 0.5 + j / L, color='white', lw=2)
# thick line between the large cells
# use clip_on=False and hide the spines to avoid that the border cells look different
for i in range(M + 1):
    ax.axvline(i - 0.5, color='skyblue', lw=4, clip_on=False)
for i in range(N + 1):
    ax.axhline(i - 0.5, color='skyblue', lw=4, clip_on=False)
ax.tick_params(length=0)
for s in ax.spines:
    ax.spines[s].set_visible(False)
plt.show()

heatmap with extra subdivisions

Upvotes: 2

Related Questions