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 .

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.


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")

Need Your Help

How to connect a J2me Midlet installed on a mobile device to a java application?

java java-me bluetooth wireless jsr82

I need help to connect a J2me midlet program to a java application on my desktop using bluethooth connection.

Weirdness in Equated Java Arrays: References vs. Pointers

java arrays pointers

Having a problem understanding what's going on n the code below. The behavior of arrays c and d is what I would expect. But what's going on with a and b? (I also tried this with normal, scalar vari...