def test_1d_density_kwarg(plot_1d, s): try: np.random.seed(0) x = np.random.normal(scale=s, size=2000) fig, ax = plt.subplots() # hist density = False: h = hist_plot_1d(ax, x, density=False, bins=np.linspace(-5.5, 5.5, 12)) bar_height = h.get_children()[len(h.get_children()) // 2].get_height() assert (bar_height == pytest.approx(1, rel=0.1)) # kde density = False: k = plot_1d(ax, x, density=False)[0] f = interp1d(k.get_xdata(), k.get_ydata(), 'cubic', assume_sorted=True) kde_height = f(0) assert (kde_height == pytest.approx(1, rel=0.1)) # hist density = True: h = hist_plot_1d(ax, x, density=True, bins=np.linspace(-5.5, 5.5, 12)) bar_height = h.get_children()[len(h.get_children()) // 2].get_height() assert (bar_height == pytest.approx(erf(0.5 / np.sqrt(2) / s), rel=0.1)) # kde density = True: k = plot_1d(ax, x, density=True)[0] f = interp1d(k.get_xdata(), k.get_ydata(), 'cubic', assume_sorted=True) kde_height = f(0) gauss_norm = 1 / np.sqrt(2 * np.pi * s**2) assert (kde_height == pytest.approx(gauss_norm, rel=0.1)) plt.close("all") except ImportError: if 'fastkde' not in sys.modules: pass
def test_hist_plot_1d(): fig, ax = plt.subplots() numpy.random.seed(0) data = numpy.random.randn(1000) for p in ['', 'astropyhist']: try: # Check heights for histtype 'bar' bars = hist_plot_1d(ax, data, histtype='bar', plotter=p) assert(numpy.all([isinstance(b, Patch) for b in bars])) assert(max([b.get_height() for b in bars]) == 1.) assert(numpy.all(numpy.array([b.get_height() for b in bars]) <= 1.)) # Check heights for histtype 'step' polygon, = hist_plot_1d(ax, data, histtype='step', plotter=p) assert(isinstance(polygon, Polygon)) trans = polygon.get_transform() - ax.transData assert(numpy.isclose(trans.transform(polygon.xy)[:, -1].max(), 1., rtol=1e-10, atol=1e-10)) assert(numpy.all(trans.transform(polygon.xy)[:, -1] <= 1.)) # Check heights for histtype 'stepfilled' polygon, = hist_plot_1d(ax, data, histtype='stepfilled', plotter=p) assert(isinstance(polygon, Polygon)) trans = polygon.get_transform() - ax.transData assert(numpy.isclose(trans.transform(polygon.xy)[:, -1].max(), 1., rtol=1e-10, atol=1e-10)) assert(numpy.all(trans.transform(polygon.xy)[:, -1] <= 1.)) # Check arguments are passed onward to underlying function bars = hist_plot_1d(ax, data, histtype='bar', color='r', alpha=0.5, plotter=p) cc = ColorConverter.to_rgba('r', alpha=0.5) assert(numpy.all([b.get_fc() == cc for b in bars])) polygon, = hist_plot_1d(ax, data, histtype='step', color='r', alpha=0.5, plotter=p) assert(polygon.get_ec() == ColorConverter.to_rgba('r', alpha=0.5)) # Check xmin xmin = -0.5 bars = hist_plot_1d(ax, data, histtype='bar', xmin=xmin, plotter=p) assert((numpy.array([b.xy[0] for b in bars]) >= -0.5).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmin=xmin) assert((polygon.xy[:, 0] >= -0.5).all()) # Check xmax xmax = 0.5 bars = hist_plot_1d(ax, data, histtype='bar', xmax=xmax, plotter=p) assert((numpy.array([b.xy[-1] for b in bars]) <= 0.5).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmax=xmax, plotter=p) assert((polygon.xy[:, 0] <= 0.5).all()) # Check xmin and xmax bars = hist_plot_1d(ax, data, histtype='bar', xmin=xmin, xmax=xmax, plotter=p) assert((numpy.array([b.xy[0] for b in bars]) >= -0.5).all()) assert((numpy.array([b.xy[-1] for b in bars]) <= 0.5).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmin=xmin, xmax=xmax, plotter=p) assert((polygon.xy[:, 0] >= -0.5).all()) assert((polygon.xy[:, 0] <= 0.5).all()) plt.close("all") except ImportError: if p == 'astropyhist' and 'astropy' not in sys.modules: pass
def plot(self, ax, paramname_x, paramname_y=None, *args, **kwargs): """Interface for 2D and 1D plotting routines. Produces a single 1D or 2D plot on an axis. Parameters ---------- ax: matplotlib.axes.Axes Axes to plot on paramname_x: str Choice of parameter to plot on x-coordinate from self.columns. paramname_y: str Choice of parameter to plot on y-coordinate from self.columns. optional, if not provided, or the same as paramname_x, then 1D plot produced. plot_type: str Must be in {'kde', 'scatter', 'hist', 'fastkde'} for 2D plots and in {'kde', 'hist', 'fastkde', 'astropyhist'} for 1D plots. optional, (Default: 'kde') ncompress: int Number of samples to use in plotting routines. optional, Default dynamically chosen q: str, float, (float, float) Plot the `q` inner posterior quantiles in 1d 'kde' plots. To plot the full range, set `q=0` or `q=1`. * if str: any of {'1sigma', '2sigma', '3sigma', '4sigma', '5sigma'} Plot within mean +/- #sigma of posterior. * if float: Plot within the symmetric confidence interval `(1-q, q)` or `(q, 1-q)`. * if tuple: Plot within the (possibly asymmetric) confidence interval `q`. optional, (Default: '5sigma') Returns ------- fig: matplotlib.figure.Figure New or original (if supplied) figure object axes: pandas.DataFrame or pandas.Series of matplotlib.axes.Axes Pandas array of axes objects """ self._set_automatic_limits() plot_type = kwargs.pop('plot_type', 'kde') do_1d_plot = paramname_y is None or paramname_x == paramname_y kwargs['label'] = kwargs.get('label', self.label) ncompress = kwargs.pop('ncompress', None) if do_1d_plot: if paramname_x in self and plot_type is not None: xmin, xmax = self._limits(paramname_x) kwargs['xmin'] = kwargs.get('xmin', xmin) kwargs['xmax'] = kwargs.get('xmax', xmax) if plot_type == 'kde': if ncompress is None: ncompress = 1000 return kde_plot_1d(ax, self[paramname_x], weights=self.weights, ncompress=ncompress, *args, **kwargs) elif plot_type == 'fastkde': x = self[paramname_x].compress(ncompress) return fastkde_plot_1d(ax, x, *args, **kwargs) elif plot_type == 'hist': return hist_plot_1d(ax, self[paramname_x], weights=self.weights, *args, **kwargs) elif plot_type == 'astropyhist': x = self[paramname_x].compress(ncompress) return hist_plot_1d(ax, x, plotter='astropyhist', *args, **kwargs) else: raise NotImplementedError("plot_type is '%s', but must be" " one of {'kde', 'fastkde', " "'hist', 'astropyhist'}." % plot_type) else: ax.plot([], []) else: if (paramname_x in self and paramname_y in self and plot_type is not None): xmin, xmax = self._limits(paramname_x) kwargs['xmin'] = kwargs.get('xmin', xmin) kwargs['xmax'] = kwargs.get('xmax', xmax) ymin, ymax = self._limits(paramname_y) kwargs['ymin'] = kwargs.get('ymin', ymin) kwargs['ymax'] = kwargs.get('ymax', ymax) if plot_type == 'kde': if ncompress is None: ncompress = 1000 x = self[paramname_x] y = self[paramname_y] return kde_contour_plot_2d(ax, x, y, weights=self.weights, ncompress=ncompress, *args, **kwargs) elif plot_type == 'fastkde': x = self[paramname_x].compress(ncompress) y = self[paramname_y].compress(ncompress) return fastkde_contour_plot_2d(ax, x, y, *args, **kwargs) elif plot_type == 'scatter': if ncompress is None: ncompress = 500 x = self[paramname_x].compress(ncompress) y = self[paramname_y].compress(ncompress) return scatter_plot_2d(ax, x, y, *args, **kwargs) elif plot_type == 'hist': x = self[paramname_x] y = self[paramname_y] return hist_plot_2d(ax, x, y, weights=self.weights, *args, **kwargs) else: raise NotImplementedError("plot_type is '%s', but must be" "in {'kde', 'fastkde'," "'scatter', 'hist'}." % plot_type) else: ax.plot([], [])
def plot(self, ax, paramname_x, paramname_y=None, *args, **kwargs): """Interface for 2D and 1D plotting routines. Produces a single 1D or 2D plot on an axis. Parameters ---------- ax: matplotlib.axes.Axes Axes to plot on paramname_x: str Choice of parameter to plot on x-coordinate from self.columns. paramname_y: str Choice of parameter to plot on y-coordinate from self.columns. optional, if not provided, or the same as paramname_x, then 1D plot produced. plot_type: str Must be in {'kde', 'scatter', 'hist', 'fastkde'} for 2D plots and in {'kde', 'hist', 'fastkde', 'astropyhist'} for 1D plots. optional, (Default: 'kde') ncompress: int Number of samples to use in plotting routines. optional, Default dynamically chosen Returns ------- fig: matplotlib.figure.Figure New or original (if supplied) figure object axes: pandas.DataFrame or pandas.Series of matplotlib.axes.Axes Pandas array of axes objects """ plot_type = kwargs.pop('plot_type', 'kde') do_1d_plot = paramname_y is None or paramname_x == paramname_y kwargs['label'] = kwargs.get('label', self.label) ncompress = kwargs.pop('ncompress', None) if do_1d_plot: if paramname_x in self and plot_type is not None: xmin, xmax = self._limits(paramname_x) if plot_type == 'kde': if ncompress is None: ncompress = 1000 return kde_plot_1d(ax, self[paramname_x], weights=self.weight, ncompress=ncompress, xmin=xmin, xmax=xmax, *args, **kwargs) elif plot_type == 'fastkde': x = self[paramname_x].compress(ncompress) return fastkde_plot_1d(ax, x, xmin=xmin, xmax=xmax, *args, **kwargs) elif plot_type == 'hist': return hist_plot_1d(ax, self[paramname_x], weights=self.weight, xmin=xmin, xmax=xmax, *args, **kwargs) elif plot_type == 'astropyhist': x = self[paramname_x].compress(ncompress) return hist_plot_1d(ax, x, plotter='astropyhist', xmin=xmin, xmax=xmax, *args, **kwargs) else: raise NotImplementedError("plot_type is '%s', but must be" " one of {'kde', 'fastkde', " "'hist', 'astropyhist'}." % plot_type) else: ax.plot([], []) else: if (paramname_x in self and paramname_y in self and plot_type is not None): xmin, xmax = self._limits(paramname_x) ymin, ymax = self._limits(paramname_y) if plot_type == 'kde': if ncompress is None: ncompress = 1000 x = self[paramname_x] y = self[paramname_y] return kde_contour_plot_2d(ax, x, y, weights=self.weight, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, ncompress=ncompress, *args, **kwargs) elif plot_type == 'fastkde': x = self[paramname_x].compress(ncompress) y = self[paramname_y].compress(ncompress) return fastkde_contour_plot_2d(ax, x, y, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, *args, **kwargs) elif plot_type == 'scatter': if ncompress is None: ncompress = 500 x = self[paramname_x].compress(ncompress) y = self[paramname_y].compress(ncompress) return scatter_plot_2d(ax, x, y, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, *args, **kwargs) elif plot_type == 'hist': x = self[paramname_x] y = self[paramname_y] return hist_plot_2d(ax, x, y, weights=self.weight, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, *args, **kwargs) else: raise NotImplementedError("plot_type is '%s', but must be" "in {'kde', 'fastkde'," "'scatter', 'hist'}." % plot_type) else: ax.plot([], [])