Exemplo n.º 1
0
    def __init__(
        self,
        x,
        y,
        z,
        data=None,
        fillna=None,
        ax=None,
        colorbar="vertical",
        im_kwargs={},
    ):
        self.ax = get_ax(ax)

        if data is None:
            data = pd.DataFrame({"x": x, "y": y, "z": z})
            x, y, z = "x", "y", "z"
        data = (data.reset_index().set_index(
            [y, x]).unstack(x)[z].sort_index(ascending=False))
        if fillna is not None:
            data.fillna(fillna)

        bounds = data.columns[0], data.columns[-1], data.index[-1], data.index[
            0]
        self.im = self.ax.imshow(data.values, extent=(bounds), **im_kwargs)

        if colorbar:
            if colorbar not in ["vertical", "horizontal"]:
                colorbar = "vertical"
            self.cbar = add_colorbar(self.im, orientation=colorbar)
        else:
            self.cbar = None
        self.data = data
Exemplo n.º 2
0
 def plot(self, ax=None, logx=False, logy=False):
     ax = get_ax(ax)
     self.power.abs().plot(ax=ax)
     ax.set_xlim([0, self.nyquist])
     if logx:
         ax.set_xscale("log")
     if logy:
         ax.set_yscale("log")
     return ax
Exemplo n.º 3
0
def plot_PSTH(data,
              ax=None,
              plot='line',
              plot_params={},
              PSTH_params={},
              **kwargs):
    ax = get_ax(ax)
    xticks, counts = PSTH(**PSTH_params).compute(data,
                                                 nrows=kwargs.get('nrows'))
    if plot == 'line':
        plot_params = ChainMap(plot_params, default_PSTHplot_line_params)
        ax.plot(xticks, counts, **plot_params)
    return ax
Exemplo n.º 4
0
def Regression(
    x,
    y,
    data=None,
    x_pred=None,
    drop_na=True,
    fitline=True,
    scatter=True,
    engine="matplotlib",
    ax=None,
    fitline_kwargs={},
    scatter_kwargs={},
):
    """ A convenience function for generating a regression plot

    Parameters
    ----------
    x, y, data, drop_na
        see simi.analysis.linear_regression.LinearRegression
    fitline: bool; default=True
        determines if a fitline is plotted
    scatter: bool; default=True
        determines if the original data is plotted
    engine: str; default='matplotlib'
    ax: Axes; default=None
    fitline_kwargs: dict-like; default={}
    scatter_kwargs: dict-like; default={}
    """
    regression_output = LinearRegression(x, y, data, drop_na, x_pred=x_pred)

    if engine == "holoviews":
        plot = _regression_holoviews(regression_output, fitline, scatter)
        return plot
    elif engine == "matplotlib":
        ax = get_ax(ax)
        if fitline:
            ax.plot(regression_output.x_pred, regression_output.y_pred,
                    **fitline_kwargs)
        if scatter:
            ax.scatter(
                regression_output.data[regression_output.x_label],
                regression_output.data[regression_output.y_label],
                **scatter_kwargs,
            )
        return ax
    else:
        raise ValueError(
            f"Engine not implemented: {engine}. Choose one of: ['holoviews','matplotlib']"
        )
Exemplo n.º 5
0
    def __init__(self, x, y, z, data=None, fillna=None, ax=None, colorbar='vertical', im_kwargs={}):
        self.ax = get_ax(ax)

        if data is None:
            data = pd.DataFrame({'x':x, 'y':y, 'z':z})
            x, y, z = 'x', 'y', 'z'
        data = data.reset_index().set_index([y, x]).unstack(x)[z].sort_index(ascending=False)
        if fillna is not None:
            data.fillna(fillna)
        
        bounds = data.columns[0], data.columns[-1], data.index[-1], data.index[0]
        self.im = self.ax.imshow(data.values, extent=(bounds), **im_kwargs)

        if colorbar:
            if colorbar not in ['vertical', 'horizontal']:
                colorbar = 'vertical'
            self.cbar = add_colorbar(self.im, orientation=colorbar)
        else:
            self.cbar = None
        self.data = data
Exemplo n.º 6
0
def Contour(x,
            y,
            z,
            cmap="bwr",
            filename=None,
            ax=None,
            colorbar="vertical",
            ax_kwargs={}):
    ax = get_ax(ax)
    ax.set_aspect("auto")

    im = ax.contourf(x, y, z, cmap=cmap)

    if colorbar:
        if colorbar not in ["vertical", "horizontal"]:
            colorbar = default_colorbar_orientation
        add_colorbar(im, colorbar)

    ax_formatting(ax, **ax_kwargs)
    return im
Exemplo n.º 7
0
def Contour(x,
            y,
            z,
            cmap='bwr',
            filename=None,
            ax=None,
            colorbar='vertical',
            ax_kwargs={}):
    ax = get_ax(ax)
    ax.set_aspect('auto')

    im = ax.contourf(x, y, z, cmap=cmap)

    if colorbar:
        if colorbar not in ['vertical', 'horizontal']:
            colorbar = default_colorbar_orientation
        add_colorbar(im, colorbar)

    ax_formatting(ax, **ax_kwargs)
    return im
Exemplo n.º 8
0
 def plot_window(self, ax=None):
     ax = get_ax(ax)
     self.window.plot(ax=ax)
Exemplo n.º 9
0
def Histogram(
    data,
    bins=10,
    range=None,
    density=False,
    proportion=False,
    multiplier=1,
    invert=False,
    engine="matplotlib",
    ax=None,
    params={},
):
    """ A convenience function for generating histograms

    Parameters
    ----------
    data: array_like
        Input data (see np.histogram)
    bins: int or sequence of scalars or str, optional; default = 10
        Defines histrogram bins (see np.histogram)
    range: (float, float), optional; default = None
        Lower and upper bounds of the bins (see np.histogram)
    density: bool, optional; default = False
        number of samples if False, density if True (see np.histogram)
        density and proportion cannot both be True
        density is such that the area under the histogram is 1 
        np.sum(frequencies * np.diff(edges)) == 1
    proportion: bool, optional; default = False
        number of samples if False, density if True (see np.histogram)
        density and proportion cannot both be True
        proportion is such that the sum of bar heights is 1 
        np.sum(frequencies) == 1
        if proportion is a numeric value, normalized to that instead
    multiplier: numeric, optional; default = 1
        A scalar to multiple all the counts by
    invert: bool, optional; default = False
        If True, all frequencies are multiplied by -1 to flip upside down
    engine: str, optional; default = 'holoviews'
        Which plotting engine is to be used. Defaults to holoviews
        Currently supported: ['holoviews']
    
    Returns
    -------
    if 'engine' is 'holoviews', returns hv.Histogram
    if 'engine' is 'matplotlib', returns ax
    """
    data = np.asarray(data)

    if proportion and density:
        raise ValueError("proportion and density cannot both be enabled")

    weights = (np.ones_like(data) * proportion /
               data.size if proportion else np.ones_like(data))
    if invert:
        weights *= -1
    weights = weights * multiplier
    frequencies, edges = np.histogram(data,
                                      bins,
                                      range,
                                      density=density,
                                      weights=weights)

    if engine == "holoviews":
        if invert:
            frequencies *= -1
        frequencies = frequencies * multiplier
        if proportion or density:
            raise NotImplementedError
        hist = _histogram_holoviews(edges, frequencies)
        return hist
    elif engine == "matplotlib":
        ax = get_ax(ax)
        if params.get("histtype") == "line":
            params.pop("histtype")
            cumulative = params.pop("cumulative", False)
            counts, edges = np.histogram(data,
                                         bins=bins,
                                         range=range,
                                         density=density,
                                         weights=weights)
            if cumulative:
                counts = np.cumsum(counts)

            align = params.pop("align", "mid")
            if align == "left":
                bin_align_points = edges[:-1]
            elif align == "right":
                bin_align_points = edges[1:]
            else:
                bin_align_points = np.mean([edges[:-1], edges[1:]], axis=0)

            orientation = params.pop("orientation", "vertical")
            if orientation == "vertical":
                ax.plot(bin_align_points, counts, **params)
            elif orientation == "horizontal":
                ax.plot(counts, bin_align_points, **params)
        else:
            ax.hist(data,
                    bins=bins,
                    range=range,
                    density=density,
                    weights=weights,
                    **params)
        return ax
    else:
        raise ValueError(
            f"Engine not implemented: {engine}. Choose one of: ['holoviews','matplotlib']"
        )
Exemplo n.º 10
0
def Raster(data, ax=None, eventplot_params={}, **kwargs):
    ax = get_ax(ax)
    eventplot_params = ChainMap(eventplot_params,
                                default_raster_eventplot_params)
    ax.eventplot(data, **eventplot_params)
    return ax