Suho Cho
Suho Cho

Reputation: 585

pyplot heatmap with text

I'm trying to draw a heatmap with MxN matrix.

x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
y = [5, 15, 25, 35]
z = [[0.31, 0.77, 0.88, 0.90, 0.79, 0.70, 0.50],
     [0.32, 0.70, 0.81, 0.85, 0.75, 0.61, 0.44],
     [0.21, 0.45, 0.64, 0.77, 0.70, 0.55, 0.23],
     [0.12, 0.30, 0.41, 0.53, 0.44, 0.41, 0.11]]

and it should be formed like the image below (with colorbar) enter image description here

Thanks.

Upvotes: 1

Views: 163

Answers (1)

Stef
Stef

Reputation: 30589

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

x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
y = [5, 15, 25, 35]
z = [[0.31, 0.77, 0.88, 0.90, 0.79, 0.70, 0.50],
     [0.32, 0.70, 0.81, 0.85, 0.75, 0.61, 0.44],
     [0.21, 0.45, 0.64, 0.77, 0.70, 0.55, 0.23],
     [0.12, 0.30, 0.41, 0.53, 0.44, 0.41, 0.11]]

fig, ax = plt.subplots()
im = ax.imshow(z,origin='lower',cmap='Blues')
ax.set_xticks(range(len(x)))
ax.set_yticks(range(len(y)))
ax.set_xticklabels(x)
ax.set_yticklabels(y)

for i in range(len(x)):
    for j in range(len(y)-1,-1,-1):
        text = ax.text(i, j, f'{z[j][i]:.2f}', ha='center', va='center', color='black')
       
ax.set_title('X-Y HEATMAP')
ax.set_xlabel('X-VALUE')
ax.set_ylabel('Y-VALUE')

enter image description here

Upvotes: 1

Related Questions