How to create a 2D heatmap in Python?

How can I plot a 2D heat map in Python?

I have an n-by-n Numpy array, where each value ranges from 0 to 1. For each (i, j) element in the array, I want to plot a square at the (i, j) coordinate in the heat map, and the color of the square should be proportional to the value at that position.

How can I achieve this using Python heat map?

Hey, I’ve worked on a few projects involving heatmaps, and a simple way to get started with a Python heat map is using the imshow() function. It’s straightforward and great for quick visualizations. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

This will generate a 16x16 grid with a ‘hot’ color map applied. Super handy for a quick visualization.

Good point, @shilpa.chandel! But if you’re looking for a bit more flexibility over the grid layout, I’d recommend pcolor(). This method gives more control, especially if you want to tweak the gridlines or add more features to your Python heat map. Check this out:

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.pcolor(a, cmap='hot')
plt.colorbar()
plt.show()

With pcolor(), you can also add a color bar to help interpret the values. It’s a great alternative if you need extra customization.

Both are solid choices! If you’re aiming for something a bit more detailed, especially for visualizing contour levels, contourf() is another powerful tool for a Python heat map. It generates a filled contour plot, which can be visually more descriptive:

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.contourf(a, cmap='hot')
plt.colorbar()
plt.show()

The filled contours make it easier to spot transitions between value ranges. I’ve found this particularly useful for datasets where patterns are more subtle.