Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot Scatter to Contour plot

I'm in the process of making a scatter plot from thousands of points in python using pyplot. My problem is that they tend to concentrate in one place, and it's just a giant blob of points.

Is there some kind of functionality to make pyplot plot points up until it reaches some critical density and then make it a contour plot?

My question is similar to this one, where the example plot has contour lines, in which the color represents the density of the plotted points.

Super cool contour plot

This is what my data looks likeLots of yellow points

like image 489
Matthew Avatar asked Nov 19 '15 01:11

Matthew


People also ask

How do you add a Colorbar to a contour plot in Python?

you have to use both contourf() and contour(). A color bar can be added to the filled contour plot using either the pyplot. colorbar() function or the figure. colorbar() method.

What is CMAP PLT scatter?

cmap: A map of colors to use in the plot.

How do you contour a plot?

A contour plot is a graphical technique for representing a 3-dimensional surface by plotting constant z slices, called contours, on a 2-dimensional format. That is, given a value for z, lines are drawn for connecting the (x,y) coordinates where that z value occurs.


1 Answers

First, you need a density estimation of you data. Depending on the method you choose, varying result can be obtained.

Let's assume you want to do gaussian density estimation, based on the example of scipy.stats.gaussian_kde, you can get the density height with:

def density_estimation(m1, m2):
    X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]                                                     
    positions = np.vstack([X.ravel(), Y.ravel()])                                                       
    values = np.vstack([m1, m2])                                                                        
    kernel = stats.gaussian_kde(values)                                                                 
    Z = np.reshape(kernel(positions).T, X.shape)
    return X, Y, Z

Then, you can plot it with contour with

X, Y, Z = density_estimation(m1, m2)

fig, ax = plt.subplots()                   

# Show density 
ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,                                                    
          extent=[xmin, xmax, ymin, ymax])

# Add contour lines
plt.contour(X, Y, Z)                                                                           

ax.plot(m1, m2, 'k.', markersize=2)    

ax.set_xlim([xmin, xmax])                                                                           
ax.set_ylim([ymin, ymax])                                                                           
plt.show()

As an alternative, you could change the marker color based on their density as shown here.

like image 90
memoselyk Avatar answered Nov 07 '22 16:11

memoselyk