# How to make matplotlib Density Map

Let's say I have two lists, x and y of same length. This length is not fixed, but always nonzero. They are x and y values of non-negative points.

I want to create a a color density map much like http://www.mathworks.com/matlabcentral/fx_files/31726/1/datadensitymap.jpg .

Here's my attempt borrowing from a few places I've found on the internet:

density = stats.gaussian_kde([x,y]) color = density([x,y]) x1 = np.array(x) y1 = np.array(y) xmin = x1.min() xmax = x1.max() ymin = y1.min() ymax = y1.max() xscale = (xmax-xmin)/100 yscale = (ymax-ymin)/100 X, Y = np.mgrid[xmin:xmax:xscale, ymin:ymax:yscale] positions = np.vstack([X.ravel(), Y.ravel()]) Z = np.reshape(density(positions).T, X.shape) cmap = plt.get_cmap("hot") plt.imshow(np.rot90(Z), cmap=cmap, extent=[xmin, xmax, ymin, ymax]) plt.scatter(x, y, c=color, cmap=cmap)

When I run this code the plot doesn't render; the title and labels are mashed together.

When I take out the call to imshow, the scatterplot shows perfectly with the density colors on the points showing correctly.

## Answers

As it turns out, the plot was rendering, but because x had values much larger than y the rendered graph had no height. Setting aspect="auto" fixed it:

plt.imshow(np.rot90(Z), cmap=cmap, extent=[xmin, xmax, ymin, ymax], aspect="auto")