# Untitled

Oct 26th, 2020
1,270
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. def find_confidence_interval(x, pdf, confidence_level):
2.     return pdf[pdf > x].sum() - confidence_level
3.
4. def density_contour(xdata, ydata, binsx, binsy, ax=None, levels_confidence=[0.68, 0.95, 0.99], range=None, **contour_kwargs):
5.     """ Create a density contour plot.
6.    Parameters
7.    ----------
8.    xdata : numpy.ndarray
9.    ydata : numpy.ndarray
10.    binsx : int
11.        Number of bins along x dimension
12.    binsy : int
13.        Number of bins along y dimension
14.    ax : matplotlib.Axes (optional)
15.        If supplied, plot the contour to this axis. Otherwise, open a new figure
16.    contour_kwargs : dict
17.        kwargs to be passed to pyplot.contour()
18.    """
19.     import scipy.optimize as so
20.     # nbins_x = len(binsx) - 1
21.     # nbins_y = len(binsy) - 1
22.     H, xedges, yedges = np.histogram2d(xdata, ydata, bins=[binsx, binsy], range=range, normed=True)
23.     x_bin_sizes = (xedges[1:] - xedges[:-1])
24.     y_bin_sizes = (yedges[1:] - yedges[:-1])
25.     pdf = (H * (x_bin_sizes * y_bin_sizes))
26.     levels = [so.brentq(find_confidence_interval, 0., 1., args=(pdf, lvl)) for lvl in levels_confidence]
27.     # one_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.68))
28.     # two_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.95))
29.     # three_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.99))
30.     # levels = [one_sigma, two_sigma, three_sigma]
31.     X, Y = 0.5 * (xedges[1:] + xedges[:-1]), 0.5 * (yedges[1:] + yedges[:-1])
32.     Z = pdf.T
33.     if ax is None:
34.         contour = plt.tricontour(X, Y, Z, levels=levels[::-1], origin="lower", **contour_kwargs)
35.     else:
36.         # contour = ax.contour(X, Y, Z, levels=levels, origin="lower", **contour_kwargs)
37.         contour = ax.contour(X, Y, Z, levels=levels[::-1], origin="lower", **contour_kwargs)
38.     return contour
RAW Paste Data