Een 2D-heatmap plotten met Matplotlib

Met Matplotlib wil ik een 2D-warmtekaart plotten. Mijn gegevens zijn een n-by-n Numpy-array, elk met een waarde tussen 0 en 1. Dus voor het (i, j) -element van deze array, wil ik een vierkant plotten op de (i, j) -coördinaat in mijn heatmap, waarvan de kleur evenredig is met de waarde van het element in de array.

Hoe kan ik dit doen?


Antwoord 1, autoriteit 100%

De functie imshow()met parameters interpolation='nearest'en cmap='hot'zouden moeten doen wat je wilt.

import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()


Antwoord 2, autoriteit 36%

Seabornneemt een groot deel van het handmatige werk uit handen en plot automatisch een verloop aan de zijkant van de kaart enz.

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()

Of je kunt zelfs driehoeken boven/links/rechts van vierkante matrices plotten, bijvoorbeeld een correlatiematrix die vierkant en symmetrisch is, dus het plotten van alle waarden zou sowieso overbodig zijn.

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()


Antwoord 3, autoriteit 14%

Ik zou matplotlib’s pcolor/pcolormeshfunctie omdat het niet-uniforme afstand tussen de gegevens toestaat.

Voorbeeld overgenomen uit matplotlib:

import matplotlib.pyplot as plt
import numpy as np
# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
plt.show()


Antwoord 4, autoriteit 5%

Zo doe je het vanuit een csv:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Load data from CSV
dat = np.genfromtxt('dat.xyz', delimiter=' ',skip_header=0)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]
# Convert from pandas dataframes to numpy arrays
X, Y, Z, = np.array([]), np.array([]), np.array([])
for i in range(len(X_dat)):
        X = np.append(X, X_dat[i])
        Y = np.append(Y, Y_dat[i])
        Z = np.append(Z, Z_dat[i])
# create x-y points to be used in heatmap
xi = np.linspace(X.min(), X.max(), 1000)
yi = np.linspace(Y.min(), Y.max(), 1000)
# Interpolate for plotting
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')
# I control the range of my colorbar by removing data 
# outside of my range of interest
zmin = 3
zmax = 12
zi[(zi<zmin) | (zi>zmax)] = None
# Create the contour plot
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
                  vmax=zmax, vmin=zmin)
plt.colorbar()  
plt.show()

waar dat.xyzis in de vorm

x1 y1 z1
x2 y2 z2
...

Other episodes