create heatmap2d from txt file

If you’re willing to do everything in Python, you can compute the histogram and build a contour plot in one script :

import numpy as np
import matplotlib.pyplot as plt

# load the data
M = np.loadtxt('datafile.dat', skiprows=1)

# compute 2d histogram
bins_x = 100
bins_y = 100
H, xedges, yedges = np.histogram2d(M[:,0], M[:,1], [bins_x, bins_y])

# xedges and yedges are each length 101 -- here we average
# the left and right edges of each bin
X, Y = np.meshgrid((xedges[1:] + xedges[:-1]) / 2,
                   (yedges[1:] + yedges[:-1]) / 2)

# make the plot, using a "jet" colormap for colors
plt.contourf(X, Y, H, cmap='jet')

plt.show()  # or plt.savefig('contours.pdf')

I just made up some test data composed of 2 Gaussians and got this result :

contour plot from 2d histogram

Leave a Comment