Home > Enterprise >  2D Array for Heatmap
2D Array for Heatmap

Time:11-17

I am trying to create a 2D array that I will use to plot a heatmap.

The array needs to be n by n and have the highest value be at its epicenter with diminishing values further away like in the diagram below.

How could I do that?

enter image description here

CodePudding user response:

You can use numpy for the array and matplotlib for creating a heatmap respectively. Something like this:


import numpy as np
import matplotlib.pyplot as plt
# creating array using numpy
array=np.ones((9,9),dtype=int)
array[1:8,1:8]=2
array[2:7,2:7]=3
array[3:6,3:6]=4
array[4,4]=5
print(array)

fig, ax = plt.subplots()
im = ax.imshow(array,cmap="PuBuGn") # cmap can be Greys, YlGnBu, PuBuGn, BuPu etc
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax,ticks=[1,2,3,4,5])
cbar.ax.set_ylabel("My bar [1-5]", rotation=-90, va="bottom")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_title("My heatmap")
fig.tight_layout()
plt.show()

CodePudding user response:

For automatically create an array, use a loop.

import numpy as np
import matplotlib.pyplot as plt
lim=100
arr=np.ones((lim,lim),dtype=int)
for i in range(1,lim):
    arr[i:len(arr)-i,i:len(arr)-i]=i 1
    
fig, ax = plt.subplots()
im = ax.imshow(arr,cmap="Purples") # cmap can be Greys, YlGnBu, PuBuGn, BuPu etc
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax,ticks=list(range(1,lim,5)))
cbar.ax.set_ylabel("My bar [1-50]", rotation=-90, va="bottom")
ax.set_xticklabels([])
ax.set_yticklabels([])

# Show all ticks and label them with the respective list entries
ax.set_title("My heatmap")
fig.tight_layout()
plt.show()
  • Related