Turn hist2d output into contours in matplotlib

Jon picture Jon · Oct 14, 2014 · Viewed 12k times · Source

I have generated some data in Python using matplotlib.hist2d. An example of the data is seen below. data

As you can see this data has some contours in it found by tracing the same color throughout the plot. I see a gamma distribution centered around 0.015. I would like to take this data and gather these contours so I can see a line trace through each color level. I tried playing around with the contour function as here

counts, xedges, yedges, Image = hist2d(x, y, bins=bins, norm=LogNorm(), range=[[0, 1], [0, 400]])
contour(counts)

but that didn't seem to produce anything.

Does anyone know the best way to get these contours? Ideally I'd like to take these contours and fit a function (like a gamma function) to them and then get the function parameters.

Thanks

Answer

ebarr picture ebarr · Oct 14, 2014

So the problem is that the image created by hist2d is plotted in data coordinates, but the contours you are trying to create are in pixel coordinates. The simple way around this is to specify the extent of the contours (i.e. rescale/reposition them in the x and y axes).

For example:

from matplotlib.colors import LogNorm
from matplotlib.pyplot import *

x = np.random.normal(5,10,100000)
y = np.random.normal(5,10,100000)
counts,ybins,xbins,image = hist2d(x,y,bins=100,norm=LogNorm())
contour(counts,extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],linewidths=3)

Will produce:

enter image description here