bwubrian
bwubrian

Reputation: 3

How to use indices of 2D array to generate heatmap with matplotlib/seaborn?

I have a 2D numpy array A that contains intensity values corresponding to each point. I am trying to generate a heatmap for these points. For example, if the value at A[3,0] is 230, then I want the square with x-value of 3 and y-value of 0 to correspond to a value of 230.

I've tried simply using the Seaborn heatmap function.

import numpy as np
import seaborn as sns

np.random.seed(0)
A = np.random.uniform(0,500,(4,3))
sns.heatmap(A, square=True)

Where A is just a 4x3 numpy array of random values. The output, however, is a region that looks like the matrix A.

enter image description here

This is a 4x3 region where each point corresponds to a point in the matrix A if it were written out. But I'm not sure how to get it such that I create a heatmap using the actual indices of the matrix as the points. The heatmap in mind would actually be 3x4 and resemble part of a coordinate plane, with x-values of [0,1,2,3] and y-values of [0,1,2].

Sorry if I've explained poorly. I might be severely misunderstanding how a heatmap works, but is there a way to do this(either with or without the heatmap function)? Thanks for reading.

Upvotes: 0

Views: 2820

Answers (1)

brentertainer
brentertainer

Reputation: 2188

I think you are not confusing what a heatmap is, but what the indices of an array represent. In a 2D array, the first index is the row, and the second index is the column. There is no explicit concept of Cartesian x- and y-coordinates.

That said, you can get what you want by creating a heatmap of the array's transpose, then setting the the limits of the x-axis and y-axis so that (0, 0) is in the bottom-left corner.

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

np.random.seed(0)
A = np.random.uniform(0,500,(4,3))
sns.heatmap(A.T, square=True)
plt.xlim(0, A.shape[0])
plt.ylim(0, A.shape[1])
plt.show()

enter image description here

Upvotes: 1

Related Questions