Пример #1
0
def plot_spatio_temporal_r2_values(dat):
    """Calculate the signed r^2 values and plot them in a heatmap.

    Parameters
    ----------
    dat : Data
        epoched data

    """
    r2 = proc.calculate_signed_r_square(dat)
    r2 *= -1
    max = np.max(np.abs(r2))
    plt.imshow(r2.T, aspect='auto', interpolation='None', vmin=-max, vmax=max, cmap='RdBu')
    ax = plt.gca()
    # TODO: sort front-back, left-right
    # use the locators to fine-tune the ticks
    mask = [True if chan.endswith('z') else False for chan in dat.axes[-1]]

    ax.yaxis.set_major_locator(ticker.FixedLocator(np.nonzero(mask)[0]))
    ax.yaxis.set_major_formatter(ticker.IndexFormatter(dat.axes[-1]))

    ax.xaxis.set_major_locator(ticker.MultipleLocator( np.max(dat.axes[-2]) // 100))
    ax.xaxis.set_major_formatter(ticker.IndexFormatter(['%.1f' % i for i in dat.axes[-2]]))

    plt.xlabel('%s [%s]' % (dat.names[-2], dat.units[-2]))
    plt.ylabel('%s [%s]' % (dat.names[-1], dat.units[-1]))
    plt.tight_layout(True)
    plt.colorbar()
    plt.grid(True)
Пример #2
0
def plot(results):
    '''
    Create a plot comparing multiple learners.
    `results` is a list of tuples containing:
        (title, expected values, actual values)
    
    All the elements in results will be plotted.
    '''
    global minmax

    # Using subplots to display the results on the same X axis
    fig, plts = plt.subplots(nrows=len(results), figsize=(8, 8))
    fig.canvas.set_window_title('Predicting data')

    # Show each element in the plots returned from plt.subplots()
    for subplot, (title, y, y_pred) in zip(plts, results):
        # Configure each subplot to have no tick marks
        # (these are meaningless for the sample dataset)
        subplot.xaxis.set_major_formatter(ticker.IndexFormatter(frame["Year"]))

        # Label the vertical axis
        subplot.set_ylabel('Trees Sold')

        # Set the title for the subplot
        subplot.set_title(title)

        # Plot the actual data and the prediction
        subplot.plot(y, 'g', label='actual')
        subplot.plot(y_pred, 'r--', label='predicted')

        # Shade the area between the predicted and the actual values
        subplot.fill_between(
            # Generate X values [0, 1, 2, ..., len(y)-2, len(y)-1]
            np.arange(0, len(y), 1),
            y,
            y_pred,
            color='r',
            alpha=0.2)

        # Mark the extent of the training data
        subplot.axvline(np.floor(len(y) * 0.8),
                        linestyle='--',
                        color='0',
                        alpha=0.2)

        # Include a legend in each subplot
        subplot.legend()

    # Let matplotlib handle the subplot layout
    fig.tight_layout()

    # ==================================
    # Display the plot in interactive UI
    plt.show()

    # Closing the figure allows matplotlib to release the memory used.
    plt.close()
Пример #3
0
def _string_coord_axis_tick_labels(string_axes, axes=None):
    """Apply tick labels for string coordinates."""

    ax = axes if axes else plt.gca()
    for axis, ticks in string_axes.items():
        formatter = mpl_ticker.IndexFormatter(ticks)
        locator = mpl_ticker.MaxNLocator(integer=True)
        this_axis = getattr(ax, axis)
        this_axis.set_major_formatter(formatter)
        this_axis.set_major_locator(locator)
Пример #4
0
    def plot(self, show_signals=True) -> Plot:
        plot = Plot()
        # TODO
        #  create dict instance attr that these calls pull values from
        #  would allow for more customization of charts

        plot.add_line(self.plotted_y_data,
                      x_data=self.plotted_x_data,
                      color='b')
        plot.add_line(self.center, x_data=self.plotted_x_data, color='k')
        plot.add_line(self.upper_action_limit,
                      x_data=self.plotted_x_data,
                      color='r')
        plot.add_line(self.lower_action_limit,
                      x_data=self.plotted_x_data,
                      color='r')
        plot.add_line(self.upper_warning_limit,
                      x_data=self.plotted_x_data,
                      color=config.ORANGE)  # orange
        plot.add_line(self.lower_warning_limit,
                      x_data=self.plotted_x_data,
                      color=config.ORANGE)
        plot.add_line(self.plus_one_stdev,
                      x_data=self.plotted_x_data,
                      color='g')
        plot.add_line(self.minus_one_stdev,
                      x_data=self.plotted_x_data,
                      color='g')

        if show_signals:
            plot.show_signals(self.signals,
                              x_data=self.plotted_x_data,
                              y_data=self.plotted_y_data)

        if self.x_labels:
            x_axis = plot.axes.xaxis
            x_axis.set_major_formatter(
                mticker.IndexFormatter([
                    f'{val.month}/{val.day}'
                    if isinstance(val, datetime) else val
                    for val in self.x_labels
                ]))

        self._format_plot(plot)

        return plot
Пример #5
0
    def plotTimeInterval(self, start, stop, normalize=False):
        # slize measures to plot
        pressureSlize = self.getPressures(withLabels=False).loc[start:stop, :]
        flowsSlize = self.getFlows(withLabels=False).loc[start:stop]
        # demandsSlize = self.getDemands(withLabels=False).loc[start:stop, :]
        labelSlize = self.getLabels().loc[start:stop]

        if normalize:
            pressureSlize = pressureSlize.apply(normalizeDf, axis=1)
            flowsSlize = flowsSlize.apply(normalizeDf, axis=1)

        # plot
        fig, ax = plt.subplots(3, sharex=True)

        # dax = demandsSlize.plot(ax=ax[0])
        # dax.set_ylabel("Demand")
        # dax.get_legend().set_visible(False)
        pax = pressureSlize.plot(ax=ax[0])
        pax.set_ylabel("Pressure")
        pax.get_legend().set_visible(False)
        fax = flowsSlize.plot(ax=ax[1])
        fax.set_ylabel("Flow")
        fax.get_legend().set_visible(False)
        lax = labelSlize.plot(ax=ax[2])
        lax.set_ylabel("Label")
        lax.get_legend().set_visible(False)

        # prettify plot
        fig.subplots_adjust(hspace=0)
        handles, labels = pax.get_legend_handles_labels()
        fig.legend(handles,
                   labels,
                   loc="center left",
                   bbox_to_anchor=(0.6, 0.5),
                   ncol=2)
        ticklabels = pressureSlize.index
        lax.xaxis.set_major_formatter(ticker.IndexFormatter(ticklabels))
        pax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))

        plt.xticks(rotation=90)
        plt.subplots_adjust(bottom=0.4)
        plt.tight_layout(rect=[0, 0, 0.6, 1])

        plt.show()
Пример #6
0
def plot_results(name, real_returns, cash, max_dd,
                 max_duration, max_dd_idx, max_duration_idx, hwm_idx):

    plt.plot(real_returns, label='log_returns')
    # plt.ylim(ymin = 0.)
    # plt.plot(normal_returns, label='normal_returns')
    # real_returns.plot()

    plt.plot((hwm_idx, max_dd_idx),
             (real_returns[hwm_idx], real_returns[max_dd_idx]), color='black')
    plt.annotate('max dd ({0:.2f}%)'.format(max_dd * 100.0),
                 xy=(max_dd_idx, real_returns[max_dd_idx]),
                 xycoords='data', xytext=(0, -50),
                 textcoords='offset points',
                 arrowprops=dict(facecolor='black', shrink=0.05))

    max_duration_start_idx = max_duration_idx - max_duration
    max_duration_x1x2 = (max_duration_start_idx, max_duration_idx)
    max_duration_y1y2 = (real_returns[max_duration_start_idx],
                         real_returns[max_duration_start_idx])

    plt.plot(max_duration_x1x2, max_duration_y1y2, color='black')
    plt.annotate('max dd duration ({} days)'.format(max_duration),
                 xy=((max_duration_start_idx + max_duration_idx) / 2,
                     real_returns[max_duration_start_idx]),
                 xycoords='data',
                 xytext=(-100, 30), textcoords='offset points',
                 arrowprops=dict(facecolor='black', shrink=0.05))

    plt.plot(cash, label='cash')

    plt.title(name)
    plt.legend()

    # Format x-axis with dates
    # dates = real_returns.index.to_pydatetime()
    dates = real_returns.index.map(lambda t: t.strftime('%Y-%m-%d'))
    plt.gca().xaxis.set_major_formatter(ticker.IndexFormatter(dates))
    plt.gcf().autofmt_xdate()

    plt.show()

    """
Пример #7
0
def showMatrix(matrix, x_array=None, y_array=None, **kwargs):
    """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added.
    :arg matrix: Matrix to be displayed.
    :type matrix: :class:`~numpy.ndarray`
    :arg x_array: Data to be plotted above the matrix.
    :type x_array: :class:`~numpy.ndarray`
    :arg y_array: Data to be plotted on the left side of the matrix.
    :type y_array: :class:`~numpy.ndarray`
    :arg percentile: A percentile threshold to remove outliers, i.e. only showing data within *p*-th 
                     to *100-p*-th percentile.
    :type percentile: float"""

    import matplotlib.pyplot as plt
    from matplotlib import cm, ticker
    from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
    from matplotlib.collections import LineCollection
    from matplotlib.pyplot import imshow, gca, sca, sci

    p = kwargs.pop('percentile', None)
    if p is not None:
        vmin = np.percentile(matrix, p)
        vmax = np.percentile(matrix, 100 - p)
    else:
        vmin = vmax = None

    W = H = 8

    ticklabels = kwargs.pop('ticklabels', None)
    allticks = kwargs.pop(
        'allticks', False
    )  # this argument is temporary and will be replaced by better implementation
    origin = kwargs.pop('origin', 'lower')

    if x_array is not None and y_array is not None:
        nrow = 2
        ncol = 2
        i = 1
        j = 1
        width_ratios = [1, W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif x_array is not None and y_array is None:
        nrow = 2
        ncol = 1
        i = 1
        j = 0
        width_ratios = [W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif isinstance(y_array, Phylo.BaseTree.Tree):
        nrow = 2
        ncol = 2
        i = 1
        j = 1
        width_ratios = [W, W]
        height_ratios = [H, H]
        aspect = 'auto'
    elif x_array is None and y_array is not None:
        nrow = 1
        ncol = 2
        i = 0
        j = 1
        width_ratios = [1, W]
        height_ratios = [H]
        aspect = 'auto'
    else:
        nrow = 1
        ncol = 1
        i = 0
        j = 0
        width_ratios = [W]
        height_ratios = [H]
        aspect = None

    main_index = (i, j)
    upper_index = (i - 1, j)
    left_index = (i, j - 1)

    complex_layout = nrow > 1 or ncol > 1
    cb = kwargs.pop('colorbar', True)

    if complex_layout:
        if cb:
            outer = GridSpec(1, 2, width_ratios=[15, 1], hspace=0.)
            gs = GridSpecFromSubplotSpec(nrow,
                                         ncol,
                                         subplot_spec=outer[0],
                                         width_ratios=width_ratios,
                                         height_ratios=height_ratios,
                                         hspace=0.,
                                         wspace=0.)

            gs_bar = GridSpecFromSubplotSpec(nrow,
                                             1,
                                             subplot_spec=outer[1],
                                             height_ratios=height_ratios,
                                             hspace=0.,
                                             wspace=0.)
        else:
            gs = GridSpec(nrow,
                          ncol,
                          width_ratios=width_ratios,
                          height_ratios=height_ratios,
                          hspace=0.,
                          wspace=0.)

    lines = []
    if nrow > 1:
        ax1 = plt.subplot(gs[upper_index])

        if isinstance(y_array, Phylo.BaseTree.Tree):
            pass

        else:
            ax1.set_xticklabels([])

            y = x_array
            x = np.arange(len(y))
            points = np.array([x, y]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            cmap = cm.jet(y)
            lcy = LineCollection(segments, array=x, linewidths=1, cmap='jet')
            lines.append(lcy)
            ax1.add_collection(lcy)

            ax1.set_xlim(x.min(), x.max())
            ax1.set_ylim(y.min(), y.max())
        ax1.axis('off')

    if ncol > 1:
        ax2 = plt.subplot(gs[left_index])

        if isinstance(y_array, Phylo.BaseTree.Tree):
            Phylo.draw(y_array, do_show=False, axes=ax2, **kwargs)
        else:

            ax2.set_xticklabels([])

            y = y_array
            x = np.arange(len(y))
            points = np.array([y, x]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            cmap = cm.jet(y)
            lcx = LineCollection(segments, array=y, linewidths=1, cmap='jet')
            lines.append(lcx)
            ax2.add_collection(lcx)
            ax2.set_xlim(y.min(), y.max())
            ax2.set_ylim(x.min(), x.max())
            ax2.invert_xaxis()

        ax2.axis('off')

    if complex_layout:
        ax3 = plt.subplot(gs[main_index])
    else:
        ax3 = gca()

    kwargs['origin'] = origin
    if not 'cmap' in kwargs:
        kwargs['cmap'] = 'jet'
    im = ax3.imshow(matrix, aspect=aspect, vmin=vmin, vmax=vmax, **kwargs)
    #ax3.set_xlim([-0.5, matrix.shape[0]+0.5])
    #ax3.set_ylim([-0.5, matrix.shape[1]+0.5])

    if ticklabels is not None:
        ax3.xaxis.set_major_formatter(ticker.IndexFormatter(ticklabels))
        if ncol == 1:
            ax3.yaxis.set_major_formatter(ticker.IndexFormatter(ticklabels))

    if allticks:
        ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
        ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
    else:
        ax3.xaxis.set_major_locator(ticker.AutoLocator())
        ax3.xaxis.set_minor_locator(ticker.AutoMinorLocator())

        ax3.yaxis.set_major_locator(ticker.AutoLocator())
        ax3.yaxis.set_minor_locator(ticker.AutoMinorLocator())

    if ncol > 1:
        ax3.yaxis.set_major_formatter(ticker.NullFormatter())

    colorbar = None
    if cb:
        if complex_layout:
            ax4 = plt.subplot(gs_bar[-1])
            colorbar = plt.colorbar(mappable=im, cax=ax4)
        else:
            colorbar = plt.colorbar(mappable=im)

    sca(ax3)
    sci(im)
    return im, lines, colorbar
Пример #8
0
def showMatrix(matrix, x_array=None, y_array=None, **kwargs):
    """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added.

    :arg matrix: matrix to be displayed
    :type matrix: :class:`~numpy.ndarray`

    :arg x_array: data to be plotted above the matrix
    :type x_array: :class:`~numpy.ndarray`

    :arg y_array: data to be plotted on the left side of the matrix
    :type y_array: :class:`~numpy.ndarray`

    :arg percentile: a percentile threshold to remove outliers, i.e. only showing data within *p*-th 
                     to *100-p*-th percentile
    :type percentile: float

    :arg interactive: turn on or off the interactive options
    :type interactive: bool
    """

    from matplotlib import ticker
    from matplotlib.gridspec import GridSpec
    from matplotlib.collections import LineCollection
    from matplotlib.pyplot import gca, sca, sci, colorbar, subplot

    p = kwargs.pop('percentile', None)
    vmin = vmax = None
    if p is not None:
        vmin = np.percentile(matrix, p)
        vmax = np.percentile(matrix, 100 - p)

    vmin = kwargs.pop('vmin', vmin)
    vmax = kwargs.pop('vmax', vmax)
    lw = kwargs.pop('linewidth', 1)

    W = H = kwargs.pop('ratio', 6)

    ticklabels = kwargs.pop('ticklabels', None)
    xticklabels = kwargs.pop('xticklabels', ticklabels)
    yticklabels = kwargs.pop('yticklabels', ticklabels)

    show_colorbar = kwargs.pop('colorbar', True)
    allticks = kwargs.pop(
        'allticks', False
    )  # this argument is temporary and will be replaced by better implementation
    interactive = kwargs.pop('interactive', True)

    cmap = kwargs.pop('cmap', 'jet')
    origin = kwargs.pop('origin', 'lower')

    tree_mode = False
    try:
        from Bio import Phylo
    except ImportError:
        raise ImportError('Phylo module could not be imported. '
                          'Reinstall ProDy or install Biopython '
                          'to solve the problem.')
    tree_mode = isinstance(y_array, Phylo.BaseTree.Tree)

    if x_array is not None and y_array is not None:
        nrow = 2
        ncol = 2
        i = 1
        j = 1
        width_ratios = [1, W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif x_array is not None and y_array is None:
        nrow = 2
        ncol = 1
        i = 1
        j = 0
        width_ratios = [W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif x_array is None and y_array is not None:
        nrow = 1
        ncol = 2
        i = 0
        j = 1
        width_ratios = [1, W]
        height_ratios = [H]
        aspect = 'auto'
    else:
        nrow = 1
        ncol = 1
        i = 0
        j = 0
        width_ratios = [W]
        height_ratios = [H]
        aspect = None

    main_index = (i, j)
    upper_index = (i - 1, j)
    left_index = (i, j - 1)

    complex_layout = nrow > 1 or ncol > 1

    ax1 = ax2 = ax3 = None

    if complex_layout:
        gs = GridSpec(nrow,
                      ncol,
                      width_ratios=width_ratios,
                      height_ratios=height_ratios,
                      hspace=0.,
                      wspace=0.)

    lines = []
    if nrow > 1:
        ax1 = subplot(gs[upper_index])

        if not tree_mode:
            ax1.set_xticklabels([])

            y = x_array
            xp, yp = interpY(y)
            points = np.array([xp, yp]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            lcy = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap)
            lines.append(lcy)
            ax1.add_collection(lcy)

            ax1.set_xlim(xp.min(), xp.max())
            ax1.set_ylim(yp.min(), yp.max())
        ax1.axis('off')

    if ncol > 1:
        ax2 = subplot(gs[left_index])

        if tree_mode:
            Phylo.draw(y_array, do_show=False, axes=ax2)
        else:
            ax2.set_xticklabels([])

            y = y_array
            xp, yp = interpY(y)
            points = np.array([yp, xp]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            lcx = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap)
            lines.append(lcx)
            ax2.add_collection(lcx)
            ax2.set_xlim(yp.min(), yp.max())
            ax2.set_ylim(xp.min(), xp.max())
            ax2.invert_xaxis()

        ax2.axis('off')

    if complex_layout:
        ax3 = subplot(gs[main_index])
    else:
        ax3 = gca()

    im = ax3.imshow(matrix,
                    aspect=aspect,
                    vmin=vmin,
                    vmax=vmax,
                    cmap=cmap,
                    origin=origin,
                    **kwargs)
    #ax3.set_xlim([-0.5, matrix.shape[0]+0.5])
    #ax3.set_ylim([-0.5, matrix.shape[1]+0.5])

    if xticklabels is not None:
        ax3.xaxis.set_major_formatter(ticker.IndexFormatter(xticklabels))
    if yticklabels is not None and ncol == 1:
        ax3.yaxis.set_major_formatter(ticker.IndexFormatter(yticklabels))

    if allticks:
        ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
        ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
    else:
        ax3.xaxis.set_major_locator(ticker.AutoLocator())
        ax3.xaxis.set_minor_locator(ticker.AutoMinorLocator())

        ax3.yaxis.set_major_locator(ticker.AutoLocator())
        ax3.yaxis.set_minor_locator(ticker.AutoMinorLocator())

    if ncol > 1:
        ax3.yaxis.set_major_formatter(ticker.NullFormatter())

    cb = None
    if show_colorbar:
        if nrow > 1:
            axes = [ax1, ax2, ax3]
            while None in axes:
                axes.remove(None)
            s = H / (H + 1.)
            cb = colorbar(mappable=im, ax=axes, anchor=(0, 0), shrink=s)
        else:
            cb = colorbar(mappable=im)

    sca(ax3)
    sci(im)

    if interactive:
        from prody.utilities import ImageCursor
        from matplotlib.pyplot import connect
        cursor = ImageCursor(ax3, im)
        connect('button_press_event', cursor.onClick)

    return im, lines, cb
Пример #9
0
def showLines(*args, **kwargs):
    """
    Show 1-D data using :func:`~matplotlib.axes.Axes.plot`. 
    
    :arg x: (optional) x coordinates. *x* can be an 1-D array or a 2-D matrix of 
            column vectors.
    :type x: `~numpy.ndarray`

    :arg y: data array. *y* can be an 1-D array or a 2-D matrix of 
            column vectors.
    :type y: `~numpy.ndarray`

    :arg dy: an array of variances of *y* which will be plotted as a 
             band along *y*. It should have the same shape with *y*.
    :type dy: `~numpy.ndarray`

    :arg lower: an array of lower bounds which will be plotted as a 
                band along *y*. It should have the same shape with *y* and should be 
                paired with *upper*.
    :type lower: `~numpy.ndarray`

    :arg upper: an array of upper bounds which will be plotted as a 
                band along *y*. It should have the same shape with *y* and should be 
                paired with *lower*.
    :type upper: `~numpy.ndarray`

    :arg alpha: the transparency of the band(s) for plotting *dy*.
    :type alpha: float

    :arg beta: the transparency of the band(s) for plotting *miny* and *maxy*.
    :type beta: float

    :arg ticklabels: user-defined tick labels for x-axis.
    :type ticklabels: list
    """

    # note for developers: this function serves as a low-level
    # plotting function which provides basic utilities for other
    # plotting functions. Therefore showFigure is not handled
    # in this function as it should be already handled in the caller.

    ticklabels = kwargs.pop('ticklabels', None)
    dy = kwargs.pop('dy', None)
    miny = kwargs.pop('lower', None)
    maxy = kwargs.pop('upper', None)
    alpha = kwargs.pop('alpha', 0.5)
    beta = kwargs.pop('beta', 0.25)
    gap = kwargs.pop('gap', False)
    labels = kwargs.pop('label', None)

    from matplotlib import cm, ticker
    from matplotlib.pyplot import figure, gca, xlim

    ax = gca()
    lines = ax.plot(*args, **kwargs)

    polys = []

    for i, line in enumerate(lines):
        color = line.get_color()
        x, y = line.get_data()

        if gap:
            x_new, y_new = addEnds(x, y)
            line.set_data(x_new, y_new)
        else:
            x_new, y_new = x, y

        if labels is not None:
            if np.isscalar(labels):
                line.set_label(labels)
            else:
                try:
                    line.set_label(labels[i])
                except IndexError:
                    raise ValueError(
                        'The number of labels ({0}) and that of y ({1}) do not match.'
                        .format(len(labels), len(line)))

        # the following function needs to be here so that line exists
        def sub_array(a, i, tag='a'):
            ndim = 0
            if a is not None:
                if np.isscalar(a[0]):
                    ndim = 1  # a plain list (array)
                else:
                    ndim = 2  # a nested list (array)
            else:
                return None

            if ndim == 1:
                _a = a
            else:
                try:
                    _a = a[i]
                except IndexError:
                    raise ValueError(
                        'The number of {2} ({0}) and that of y ({1}) do not match.'
                        .format(len(miny), len(line), tag))

            if len(_a) != len(y):
                raise ValueError(
                    'The shapes of {2} ({0}) and y ({1}) do not match.'.format(
                        len(_miny), len(y), tag))
            return _a

        if miny is not None and maxy is not None:
            _miny = sub_array(miny, i)
            _maxy = sub_array(maxy, i)

            if gap:
                _, _miny = addEnds(x, _miny)
                _, _maxy = addEnds(x, _maxy)

            poly = ax.fill_between(x_new,
                                   _miny,
                                   _maxy,
                                   alpha=beta,
                                   facecolor=color,
                                   edgecolor=None,
                                   linewidth=1,
                                   antialiased=True)
            polys.append(poly)

        if dy is not None:
            _dy = sub_array(dy, i)

            if gap:
                _, _dy = addEnds(x, _dy)

            poly = ax.fill_between(x_new,
                                   y_new - _dy,
                                   y_new + _dy,
                                   alpha=alpha,
                                   facecolor=color,
                                   edgecolor=None,
                                   linewidth=1,
                                   antialiased=True)
            polys.append(poly)

    ax.margins(x=0)
    if ticklabels is not None:
        if callable(ticklabels):
            ax.get_xaxis().set_major_formatter(
                ticker.FuncFormatter(ticklabels))
        else:
            ax.get_xaxis().set_major_formatter(
                ticker.IndexFormatter(ticklabels))

    ax.xaxis.set_major_locator(ticker.AutoLocator())
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())

    return lines, polys
Пример #10
0
def makePlotFromRuleset(ruleset,
                        allRules=False,
                        filepath='results/temporary_ruleset_plot',
                        viewResults=True,
                        saveResults=False):
    """
    Plots a rule set's similarity matrix of rule interactions and dominances.

    **Args**:
        **ruleset**: :class:`rules.Ruleset` object that contains the
        list of rules and the rule interaction arrays.

    **kwargs**:
        **allRules**: (Optional) If true, shows even interactions that never
        occur because rule definitions are mutually exclusive. 'True' gives
        the most accurate plot, but can be overwhelminly busy if the ruleset is
        large (>5 rules or so). Default False.

        **filepath**: (Optional) Path/name at which to save plot. Default
        ``results/temporary_rule_plot``.

        **viewResults**: (Optional) If true, displays plot immediately after
        creation. Default True.

        **saveResults**: (Optional) If true, save plot. Default False.

    """
    if __name__ == '__main__':
        calledFromInterpreter = True
    else:
        calledFromInterpreter = False

    if filepath != 'results/temporary_ruleset_plot':
        saveResults = True

    #What rules are we plotting here?
    #For x:
    these_rules = ruleset.rulelist
    xticks = [a.__class__.__name__ for a in these_rules]

    #For y: What are the rules with all offsets that we're plotting here
    these_rules_offset = [False]
    max_rule_length, min_rule_length = rules.rule_max_min(these_rules)
    for r in these_rules:
        for o in range(1 - r.size, max_rule_length):
            these_rules_offset.append((r, o))
        these_rules_offset.append(False)
    yticks = [' ' for x in range(1 + len(these_rules_offset))]
    for x in range(len(these_rules_offset)):
        if these_rules_offset[x]:
            (r, o) = these_rules_offset[x]
            yticks[x] = '%s (offset %s)' % (r.__class__.__name__, str(o))

    #Set up the plot
    plottitle = (unicode('Matrix of rule interactions from rule set "') +
                 unicode(str(ruleset.name)) + unicode('"'))
    fig = plt.figure()
    ax = fig.add_subplot(111, title=plottitle)
    ax.set_axisbelow(True)

    # Starting x value
    current_x = 0

    rule_bar_height = 2.3 / (8 + max_rule_length * 2.0
                             )  # To keep bars from overlapping, set 1.8 to 1
    rule_jump = 3 * max_rule_length - 1

    # For each rule in the ruleset...
    for i in range(len(these_rules)):
        ruleA = these_rules[i]

        # ...draw rule column
        rule_start_x = current_x + max_rule_length
        _makerule(ax, rule_start_x, ruleA.size, H=2 * len(yticks) + 2)

        # ...matched against every other rule in the ruleset
        for j in range(len(these_rules)):
            ruleB = these_rules[j]

            # ...in every possible offset possibility
            all_o = range(-1 * (ruleB.size - 1), ruleA.size)
            for o in all_o:
                keycolor = 'never'

                if (ruleB, o) in ruleset.coexistence_array[ruleA]:
                    keycolor = 'unknown'

                if (ruleB, o, 'coexist') in ruleset.coexistence_array[ruleA]:
                    keycolor = 'coexist'

                if (ruleB, o, 'conflict') in ruleset.coexistence_array[ruleA]:
                    keycolor = 'conflict'

                if ruleB == ruleA and o == 0:
                    keycolor = 'self'

                #Show all the rules, or just the ones that can coexist?
                if allRules == True:
                    this_y = these_rules_offset.index((ruleB, o))
                    _makeruleline(
                        ax,
                        rule_start_x + o,
                        this_y,
                        ruleB.size,
                        H=rule_bar_height,
                        existance=keycolor,
                    )
                elif keycolor != 'never':
                    this_y = these_rules_offset.index((ruleB, o))
                    _makeruleline(
                        ax,
                        rule_start_x + o,
                        this_y,
                        ruleB.size,
                        H=rule_bar_height,
                        existance=keycolor,
                    )

        current_x = current_x + rule_jump

    #Time to format plot!
    if ruleset.name == 'Saint Lambert (Full)':
        yticks = [y.strip('SLRule_') for y in yticks]

    #Deal with y-axis
    ax.set_ylabel('Rules')
    ax.yaxis.set_major_locator(mpltick.MultipleLocator(1))
    ax.yaxis.set_minor_locator(mpltick.MultipleLocator(1))

    ax.yaxis.set_minor_formatter(mpltick.IndexFormatter(yticks))
    ax.yaxis.set_major_formatter(mpltick.NullFormatter())
    ax.set_ylim(0, len(yticks) - 2)

    #Deal with x-axis
    ax.set_xlabel('Rules \n(Each vertical dotted ' + \
                    'line represents a single bass note to be figured)')
    ax.set_xlim(0, rule_jump * len(xticks))
    ax.xaxis.set_major_locator(
        mpltick.IndexLocator(rule_jump, max_rule_length - 1))
    ax.xaxis.set_minor_locator(mpltick.MultipleLocator(1))
    ax.set_xticklabels(xticks, ha='left')
    ax.xaxis.grid(True, which='minor')
    ax.grid(True, ls='--')

    #Add legend
    lgd = _makerulelegend(ax, type='ruleset', allRules=allRules)

    #Make sure image is sized in accordance with the number of rows/columns.
    fig.set_size_inches(3 * len(xticks), .5 * len(yticks))

    #Save it?
    if saveResults:
        filepath = filepath + '.pdf'
        fig.savefig(filepath,
                    dpi=fig.dpi,
                    bbox_extra_artists=(lgd, ),
                    bbox_inches='tight')
        print 'saved at %s' % filepath

        #Open saved version?
        if viewResults:
            os.system("open " + filepath)

    #Show it?
    if viewResults == True and calledFromInterpreter == True:
        fig.show()
Пример #11
0
def eviction_stat_reuse_dist_plot(reader,
                                  algorithm,
                                  cache_size,
                                  mode,
                                  time_interval,
                                  cache_params=None,
                                  **kwargs):
    """

    :param reader:
    :param algorithm:
    :param cache_size:
    :param mode:
    :param time_interval:
    :param cache_params:
    :param kwargs:
    :return:
    """
    plot_params = prepPlotParams(
        "reuse distance of evicted elements by {}".format(algorithm),
        "time({})".format(mode), "reuse dist/cache size",
        "eviction_stat_reuse_dist_{}_{}_{}_{}_{}_{}.png".format(
            reader.file_loc[reader.file_loc.rfind('/') + 1:], algorithm,
            cache_size, mode, time_interval, cache_params), **kwargs)

    alg = cache_alg_mapping[algorithm.lower()]
    assert alg == "Optimal", "Currently only Optimal is supported"

    # get reuse distance of evicted elements by given algorithm
    rd_array = mimircache.c_eviction_stat.get_stat(reader.cReader,
                                                   algorithm=alg,
                                                   cache_size=cache_size,
                                                   stat_type="reuse_dist")

    # generate break points for bucketing the reuse_dist array
    bp = cHeatmap().get_breakpoints(reader, mode, time_interval)

    pos = 1
    count = 0
    matrix = np.zeros((len(bp), 20))

    for i in range(len(rd_array)):
        # no eviction at this timestamp
        if rd_array[i] < 0:
            if i == bp[pos]:
                for j in range(20):
                    if count:
                        matrix[pos - 1][j] /= count
                    else:
                        matrix[pos - 1][j] = np.nan
                pos += 1
                count = 0
            continue

        # check the bucket for the reuse dist of the evicted element
        y = float(rd_array[i]) / cache_size
        if y < 1:
            y = ceil(y * 10)
        elif y > 10:
            y = 19
        else:
            y = ceil(y) + 9
        matrix[pos - 1][y] += 1
        count += 1

        if i == bp[pos]:
            for j in range(20):
                matrix[pos - 1][j] /= count
            pos += 1
            count = 0

        # y could be zero, which means originally rd_array[i]=0, meaning MRU

    for j in range(20):
        if count != 0:
            matrix[pos - 1][j] /= count
        else:
            matrix[pos - 1][j] = np.nan

    majorLocator = MultipleLocator(2)
    minorLocator = MultipleLocator(1)

    xticks = ticker.FuncFormatter(
        lambda x, pos: '{:2.0f}%'.format(x * 100 / len(bp)))
    yticks = ticker.IndexFormatter([
        0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0,
        5.0, 6.0, 7.0, 8.0, 9.0, 10.0
    ])

    plt.gca().xaxis.set_major_formatter(xticks)
    plt.gca().yaxis.set_major_formatter(yticks)
    plt.gca().yaxis.set_major_locator(majorLocator)
    plt.gca().yaxis.set_minor_locator(minorLocator)

    img = plt.imshow(matrix.T,
                     interpolation='nearest',
                     origin='lower',
                     aspect='auto',
                     vmin=0,
                     vmax=1)
    cb = plt.colorbar(img)
    plt.title(plot_params['title'])
    plt.xlabel(plot_params['xlabel'])
    plt.ylabel(plot_params['ylabel'])
    plt.savefig(plot_params['figname'], dpi=600)
    try:
        plt.show()
    except:
        pass
    plt.clf()
    INFO("plot is saved at the same directory")
Пример #12
0
 def test_formatting(self, x, label):
     formatter = mticker.IndexFormatter(['label0', 'label1', 'label2'])
     assert formatter(x) == label
Пример #13
0
 def test_formatting(self, x, label):
     with cbook._suppress_matplotlib_deprecation_warning():
         formatter = mticker.IndexFormatter(['label0', 'label1', 'label2'])
     assert formatter(x) == label
Пример #14
0
def showData(*args, **kwargs):
    """
    Show data using :func:`~matplotlib.axes.Axes.plot`. 
    
    :arg x: (optional) x coordinates. *x* can be an 1-D array or a 2-D matrix of 
    column vectors.
    :type x: `~numpy.ndarray`

    :arg y: data array. *y* can be an 1-D array or a 2-D matrix of 
    column vectors.
    :type y: `~numpy.ndarray`

    :arg dy: an array of variances of *y* which will be plotted as a 
    band along *y*. It should have the same shape with *y*.
    :type dy: `~numpy.ndarray`

    :arg alpha: the transparency of the band(s).
    :type alpha: float

    :arg ticklabels: user-defined tick labels for x-axis.
    :type ticklabels: list
    """

    # note for developers: this function serves as a low-level
    # plotting function which provides basic utilities for other
    # plotting functions. Therefore showFigure is not handled
    # in this function as it should be already handled in the caller.

    ticklabels = kwargs.pop('ticklabels', None)
    dy = kwargs.pop('dy', None)
    alpha = kwargs.pop('alpha', 0.5)
    gap = kwargs.pop('gap', False)

    from matplotlib import cm, ticker
    from matplotlib.pyplot import figure, gca, xlim

    ax = gca()
    lines = ax.plot(*args, **kwargs)

    polys = []
    if dy is not None:
        dy = np.array(dy)
        if dy.ndim == 1:
            n, = dy.shape
            m = 1
        elif dy.ndim == 2:
            n, m = dy.shape
        else:
            raise ValueError('dy should be either 1-D or 2-D.')

        for i, line in enumerate(lines):
            color = line.get_color()
            x, y = line.get_data()
            if m != 1 and m != len(lines) or n != len(y):
                raise ValueError('The shapes of dy and y do not match.')

            if dy.ndim == 1:
                _dy = dy
            else:
                _dy = dy[:, i]

            if gap:
                x_new, y_new = addBreaks(x, y)
                line.set_data(x_new, y_new)
                _, _dy = addBreaks(x, _dy)
            else:
                x_new, y_new = x, y

            poly = ax.fill_between(x_new,
                                   y_new - _dy,
                                   y_new + _dy,
                                   alpha=alpha,
                                   facecolor=color,
                                   edgecolor=None,
                                   linewidth=1,
                                   antialiased=True)
            polys.append(poly)

    ax.margins(x=0)
    if ticklabels is not None:
        ax.get_xaxis().set_major_formatter(ticker.IndexFormatter(ticklabels))

    ax.xaxis.set_major_locator(ticker.AutoLocator())
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())

    return lines, polys
Пример #15
0
def trading_annotation(df,
                       strategy_name,
                       ticker_code,
                       params,
                       uid,
                       formation_date=1,
                       dpi=None):
    '''
    df <pd.DataFrame>: a DataFrame object, containing 'Buy' and 'Sell' columns for annotation.
    strategy_name <str>: The strategy name for finding the dedicated column. eg 'Morning Doji Star', 'Three Black Crows'.
    params <dict / list? / pd.DataFrame?>: parameters for the dedicated strategy. Will be displayed in the exported chart.
    uid <str>: Thd unique id for the parameter combination. eg '001', '002'.
    formation_date <int>: To be decided whether include this or not.
    dpi <int>: The dpi of the exported image. If the image is not big and want a clearer image, user could try to set this option to 300 or 400.
               If the image is too large (displaying all historical data), just set dpi to None (default is 75).
    '''
    df = df.copy()
    ticker_code = str(ticker_code)
    h_size = len(df) // 20
    fig, ax = plt.subplots(dpi=dpi)
    mpl_finance.candlestick2_ohlc(ax,
                                  df['open'],
                                  df['high'],
                                  df['low'],
                                  df['close'],
                                  width=0.6,
                                  colorup='green',
                                  colordown='red')
    signal_annotation = df[df[strategy_name]]
    buy_annotation = df[df['Buy']]
    sell_annotation = df[df['Sell']]

    # Annotating the graph.
    # Yellow indicates detection of the signal, Green indicates the buying action, Red indicates the selling action.
    for i in signal_annotation.index:
        pos1 = i - formation_date + 0.5
        pos2 = i + 0.5
        ax.axvspan(pos1, pos2, fill=True, alpha=0.3, color='yellow')
    for i in buy_annotation.index:
        pos1 = i - formation_date + 0.5
        pos2 = i + 0.5
        ax.axvspan(pos1, pos2, fill=True, alpha=0.3, color='green')
    for i in sell_annotation.index:
        pos1 = i - formation_date + 0.5
        pos2 = i + 0.5
        ax.axvspan(pos1, pos2, fill=True, alpha=0.3, color='red')
    ax.xaxis.set_major_formatter(ticker.IndexFormatter(df['date_time']))
    fig.autofmt_xdate()

    # Adding parameter dict to the graph.
    try:
        if type(params) == dict:
            for y, key in enumerate(params):
                ax.text(0.01,
                        0.9 - y / (2 * len(params)),
                        f'{key}: {params[key]}',
                        horizontalalignment='left',
                        verticalalignment='top',
                        transform=ax.transAxes)
        if type(params) == list:
            for i in range(len(params)):
                ax.text(0.01,
                        0.9 - i / (2 * len(params)),
                        f'{i}: {params[i]}',
                        horizontalalignment='left',
                        verticalalignment='top',
                        transform=ax.transAxes)
    except:
        pass
    plt.title(f'{strategy_name}: {ticker_code}')
    fig.savefig(f'graph_{ticker_code}_{strategy_name}_{uid}_.png')
    plt.show()
all_trajects_average.plot()
ax.set_xlabel("Number of flips")
ax.yaxis.set_major_formatter(tick.StrMethodFormatter('${x:,.0f}'))
ax.set_title("100,000 trajectories - 60 flips")
fig.savefig('images/100,000 trajectories - 60 flips.png')

# Now make histograms. First, make the histogram of the 100,000 trajectory end values, and then of only the people that made more than $10,000.

fig, ax = plt.subplots()
(all_trajects_end_vals / 1000000).hist(grid=False, bins=200)
ax.set_yscale("log")
ax.yaxis.set_major_formatter(tick.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_major_locator(tick.MultipleLocator(1))
ax.xaxis.set_major_formatter(
    tick.IndexFormatter([
        '$0', '$1M', '$2M', '$3M', '$4M', '$5M', '$6M', '$7M', '$8M', '$9M',
        '$10M'
    ]))
ax.set_xlabel("Dollars won")
ax.set_ylabel("Number of players")
ax.set_title("Histogram of 100,000 trajectories,  60 flips each")
fig.savefig('images/Histogram 100,000 trajectories - 60 flips.png')

fig, ax = plt.subplots()
(all_trajects_end_vals[all_trajects_end_vals > 10000] / 1000000).hist(
    color="maroon", grid=False, bins=200)
ax.set_yscale("log")
ax.yaxis.set_major_formatter(tick.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_major_locator(tick.MultipleLocator(1))
ax.xaxis.set_major_formatter(
    tick.IndexFormatter([
        '$0', '$1M', '$2M', '$3M', '$4M', '$5M', '$6M', '$7M', '$8M', '$9M',
Пример #17
0
def cartography(symbol,
                dataframe,
                cheese=None,
                adj=None,
                pivot_points=dict(),
                chart_path='./charts/active.png',
                *ignore):
    """Charting for IVy candles."""
    global plt
    plt.close('all')
    if verbose: print(f'Cartography: creating chart for {symbol}...')
    timestamps = dataframe.index.tolist()
    data_len = len(timestamps)
    data_range = range(data_len)
    cdl_open = dataframe['open'].tolist()
    cdl_high = dataframe['high'].tolist()
    cdl_low = dataframe['low'].tolist()
    cdl_close = dataframe['close'].tolist()
    cdl_vol = dataframe['volume'].tolist()
    cdl_wema = dataframe['money_wema'].tolist()
    cdl_mid = dataframe['money_mid'].tolist()
    cdl_dh = dataframe['money_dh'].tolist()
    cdl_dl = dataframe['money_dl'].tolist()
    vol_wema = dataframe['volume_wema'].tolist()
    vol_mid = dataframe['volume_mid'].tolist()
    vol_dh = dataframe['volume_dh'].tolist()
    fs = (19.20, 10.80)
    dpi = 100
    fig = plt.figure(figsize=fs, dpi=dpi, constrained_layout=False)
    sargs = dict(ncols=1, nrows=2, figure=fig, height_ratios=[4, 1])
    spec = gridspec.GridSpec(**sargs)
    ax1 = fig.add_subplot(spec[0, 0])
    ax2 = fig.add_subplot(spec[1, 0], sharex=ax1)
    plt.xticks(data_range, timestamps, rotation=21, fontweight='bold')
    plt.subplots_adjust(left=0.08,
                        bottom=0.20,
                        right=0.92,
                        top=0.95,
                        wspace=0,
                        hspace=0.08)
    ax1.grid(True, color=(0.3, 0.3, 0.3))
    ax1.set_ylabel('Price', fontweight='bold')
    ax1.set_xlim(((data_range[0] - 2), (data_range[-1] + 2)))
    ylim_low = min(cdl_low)
    ylim_high = max(cdl_high)
    ax1.set_ylim((ylim_low * 0.98, ylim_high * 1.02))
    ax1.set_yticks(cdl_close)
    ax1.set_yticklabels(cdl_close)
    ax1.yaxis.set_major_formatter(mticker.EngFormatter())
    ax1.yaxis.set_major_locator(mticker.AutoLocator())
    ax1.xaxis.set_major_formatter(mticker.IndexFormatter(timestamps))
    ax1.xaxis.set_major_locator(mticker.AutoLocator())
    ax2.grid(True, color=(0.4, 0.4, 0.4))
    ax2.set_ylabel('Volume', fontweight='bold')
    ax2.yaxis.set_major_formatter(mticker.EngFormatter())
    ax2.yaxis.set_major_locator(mticker.AutoLocator())
    xticks = ax1.xaxis.get_ticklabels()
    plt.setp(xticks[:], visible=False)
    # Dynamic width stuff
    tbb = ax1.get_tightbbox(fig.canvas.get_renderer()).get_points()
    xb = tbb[1][0] - tbb[0][0]
    wid_base = (xb / data_len) * 0.5
    wid_wick = wid_base * 0.21
    wid_cdls = wid_base * 0.89
    wid_line = wid_base * 0.34
    # Pivot Points plots
    pivots = list(pivot_points.keys())
    if len(pivots) > 0:
        freqs = list(pivot_points.values())
        f_min = min(freqs)
        f_max = max(freqs)
        shades = dict()
        for i in range(f_max - f_min):
            shades[i + f_min] = round(((f_max - i) / f_max), 2)
        pkws = {'linestyle': 'solid', 'linewidth': wid_line}
        for price in pivots:
            shade = 0
            freq = pivot_points[price]
            for f in shades:
                if f <= freq:
                    shade = 1 - shades[f]
                else:
                    break
            pkws['color'] = (0.25, 0, 0.25, shade)
            ax1.plot((0, data_len), (price, price), **pkws)
    # Per candle plots
    signal_y = [min(cdl_dl), max(cdl_dh)]
    for i in data_range:
        x_loc = [i, i]
        # Signals
        if cheese:
            cdl_date = timestamps[i].strftime('%Y-%m-%d %H:%M')
            lw = 1 + data_range[-1]
            sig_args = dict(linestyle='solid', linewidth=wid_base)
            if cdl_date in cheese:
                buy_sig = cheese[cdl_date]['buy']
                sell_sig = cheese[cdl_date]['sell']
                for sig in buy_sig:
                    if sig[0] == symbol:
                        sig_args['color'] = (0, 1, 0, 0.5)
                        ax1.plot(x_loc, signal_y, **sig_args)
                for sig in sell_sig:
                    if sig[0] == symbol:
                        sig_args['color'] = (1, 0, 0, 0.5)
                        ax1.plot(x_loc, signal_y, **sig_args)
        # Candles
        wick_data = [cdl_low[i], cdl_high[i]]
        candle_data = [cdl_close[i], cdl_open[i]]
        ax1.plot(x_loc,
                 wick_data,
                 color='white',
                 linestyle='solid',
                 linewidth=wid_wick,
                 alpha=1)
        if cdl_close[i] > cdl_open[i]:
            cdl_color = (0.33, 1, 0.33, 1)
        else:
            cdl_color = (1, 0.33, 0.33, 1)
        ax1.plot(x_loc,
                 candle_data,
                 color=cdl_color,
                 linestyle='solid',
                 linewidth=wid_cdls,
                 alpha=1)
        # Volume
        volume_data = [0, cdl_vol[i]]
        ax2.plot(x_loc,
                 volume_data,
                 color=(0.33, 0.33, 1, 1),
                 linestyle='solid',
                 linewidth=wid_cdls)
    # Per sample plots
    pkws = {'linestyle': 'solid', 'linewidth': wid_line}
    pkws['label'] = f'Money: {round(cdl_wema[-1], 2)}'
    pkws['color'] = (0.4, 0.7, 0.4, 0.8)
    ax1.plot(data_range, cdl_wema, **pkws)
    pkws['label'] = None
    ax2.plot(data_range, vol_wema, **pkws)
    pkws['label'] = f'Mid: {round(cdl_mid[-1], 2)}'
    pkws['color'] = (0.7, 0.7, 1, 0.7)
    ax1.plot(data_range, cdl_mid, **pkws)
    pkws['label'] = None
    ax2.plot(data_range, vol_mid, **pkws)
    pkws['linestyle'] = 'dotted'
    pkws['linewidth'] = wid_line * 0.67
    pkws['label'] = f'DevHigh: {round(cdl_dh[-1], 2)}'
    ax1.plot(data_range, cdl_dh, **pkws)
    pkws['label'] = None
    ax2.plot(data_range, vol_dh, **pkws)
    pkws['label'] = f'DevLow: {round(cdl_dl[-1], 2)}'
    ax1.plot(data_range, cdl_dl, **pkws)
    # Finalize
    ts = timestamps[-1].strftime('%Y-%m-%d %H:%M')
    res = adj if adj else 'None'
    rnc = round(cdl_close[-1], 3)
    t = f'[ {rnc} ]   {symbol}  @  {ts} (resample: {res})'
    fig.suptitle(t, fontsize=18)
    fig.legend(ncol=4, loc='lower center', fontsize='xx-large', fancybox=True)
    plt.savefig(str(chart_path), dpi=dpi)
    plt.close(fig)
    if verbose: print("Cartography: chart's done!")
    return False
Пример #18
0
def showMatrix(matrix, x_array=None, y_array=None, **kwargs):
    """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added.

    :arg matrix: matrix to be displayed
    :type matrix: :class:`~numpy.ndarray`

    :arg x_array: data to be plotted above the matrix
    :type x_array: :class:`~numpy.ndarray`

    :arg y_array: data to be plotted on the left side of the matrix
    :type y_array: :class:`~numpy.ndarray`

    :arg percentile: a percentile threshold to remove outliers, i.e. only showing data within *p*-th 
                     to *100-p*-th percentile
    :type percentile: float

    :arg interactive: turn on or off the interactive options
    :type interactive: bool

    :arg xtickrotation: how much to rotate the xticklabels in degrees
                        default is 0
    :type xtickrotation: float
    """

    from matplotlib import ticker
    from matplotlib.gridspec import GridSpec
    from matplotlib.collections import LineCollection
    from matplotlib.pyplot import gca, sca, sci, colorbar, subplot

    from .drawtools import drawTree

    p = kwargs.pop('percentile', None)
    vmin = vmax = None
    if p is not None:
        vmin = np.percentile(matrix, p)
        vmax = np.percentile(matrix, 100-p)
    
    vmin = kwargs.pop('vmin', vmin)
    vmax = kwargs.pop('vmax', vmax)
    vcenter = kwargs.pop('vcenter', None)
    norm = kwargs.pop('norm', None)

    if vcenter is not None and norm is None:
        if PY3K:
            try:
                from matplotlib.colors import DivergingNorm
            except ImportError:
                from matplotlib.colors import TwoSlopeNorm as DivergingNorm

            norm = DivergingNorm(vmin=vmin, vcenter=0., vmax=vmax)
        else:
            LOGGER.warn('vcenter cannot be used in Python 2 so norm remains None')

    lw = kwargs.pop('linewidth', 1)
    
    W = H = kwargs.pop('ratio', 6)

    ticklabels = kwargs.pop('ticklabels', None)
    xticklabels = kwargs.pop('xticklabels', ticklabels)
    yticklabels = kwargs.pop('yticklabels', ticklabels)

    xtickrotation = kwargs.pop('xtickrotation', 0.)

    show_colorbar = kwargs.pop('colorbar', True)
    cb_extend = kwargs.pop('cb_extend', 'neither')
    allticks = kwargs.pop('allticks', False) # this argument is temporary and will be replaced by better implementation
    interactive = kwargs.pop('interactive', True)

    cmap = kwargs.pop('cmap', 'jet')
    origin = kwargs.pop('origin', 'lower')

    try: 
        from Bio import Phylo
    except ImportError:
        raise ImportError('Phylo module could not be imported. '
            'Reinstall ProDy or install Biopython '
            'to solve the problem.')
    tree_mode_y = isinstance(y_array, Phylo.BaseTree.Tree)
    tree_mode_x = isinstance(x_array, Phylo.BaseTree.Tree)

    if x_array is not None and y_array is not None:
        nrow = 2; ncol = 2
        i = 1; j = 1
        width_ratios = [1, W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif x_array is not None and y_array is None:
        nrow = 2; ncol = 1
        i = 1; j = 0
        width_ratios = [W]
        height_ratios = [1, H]
        aspect = 'auto'
    elif x_array is None and y_array is not None:
        nrow = 1; ncol = 2
        i = 0; j = 1
        width_ratios = [1, W]
        height_ratios = [H]
        aspect = 'auto'
    else:
        nrow = 1; ncol = 1
        i = 0; j = 0
        width_ratios = [W]
        height_ratios = [H]
        aspect = kwargs.pop('aspect', None)

    main_index = (i, j)
    upper_index = (i-1, j)
    left_index = (i, j-1)

    complex_layout = nrow > 1 or ncol > 1

    ax1 = ax2 = ax3 = None

    if complex_layout:
        gs = GridSpec(nrow, ncol, width_ratios=width_ratios, 
                      height_ratios=height_ratios, hspace=0., wspace=0.)

    ## draw matrix
    if complex_layout:
        ax3 = subplot(gs[main_index])
    else:
        ax3 = gca()
    
    im = ax3.imshow(matrix, aspect=aspect, vmin=vmin, vmax=vmax, 
                    norm=norm, cmap=cmap, origin=origin, **kwargs)
                    
    #ax3.set_xlim([-0.5, matrix.shape[0]+0.5])
    #ax3.set_ylim([-0.5, matrix.shape[1]+0.5])

    if xticklabels is not None:
        ax3.xaxis.set_major_formatter(ticker.IndexFormatter(xticklabels))
    if yticklabels is not None and ncol == 1:
        ax3.yaxis.set_major_formatter(ticker.IndexFormatter(yticklabels))

    if allticks:
        ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
        ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.))
    else:
        locator = ticker.AutoLocator()
        locator.set_params(integer=True)
        minor_locator = ticker.AutoMinorLocator()

        ax3.xaxis.set_major_locator(locator)
        ax3.xaxis.set_minor_locator(minor_locator)

        locator = ticker.AutoLocator()
        locator.set_params(integer=True)
        minor_locator = ticker.AutoMinorLocator()
        
        ax3.yaxis.set_major_locator(locator)
        ax3.yaxis.set_minor_locator(minor_locator)

    if ncol > 1:
        ax3.yaxis.set_major_formatter(ticker.NullFormatter())
    
    ## draw x_ and y_array
    lines = []

    if nrow > 1:
        ax1 = subplot(gs[upper_index])

        if tree_mode_x:
            Y, X = drawTree(x_array, label_func=None, orientation='vertical', 
                            inverted=True)
            miny = min(Y.values())
            maxy = max(Y.values())

            minx = min(X.values())
            maxx = max(X.values())

            ax1.set_xlim(minx-.5, maxx+.5)
            ax1.set_ylim(miny, 1.05*maxy)
        else:
            ax1.set_xticklabels([])
            
            y = x_array
            xp, yp = interpY(y)
            points = np.array([xp, yp]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            lcy = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap)
            lines.append(lcy)
            ax1.add_collection(lcy)

            ax1.set_xlim(xp.min()-.5, xp.max()+.5)
            ax1.set_ylim(yp.min(), yp.max())

        if ax3.xaxis_inverted():
            ax2.invert_xaxis()

        ax1.axis('off')

    if ncol > 1:
        ax2 = subplot(gs[left_index])
        
        if tree_mode_y:
            X, Y = drawTree(y_array, label_func=None, inverted=True)
            miny = min(Y.values())
            maxy = max(Y.values())

            minx = min(X.values())
            maxx = max(X.values())

            ax2.set_ylim(miny-.5, maxy+.5)
            ax2.set_xlim(minx, 1.05*maxx)
        else:
            ax2.set_xticklabels([])
            
            y = y_array
            xp, yp = interpY(y)
            points = np.array([yp, xp]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            lcx = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap)
            lines.append(lcx)
            ax2.add_collection(lcx)
            ax2.set_xlim(yp.min(), yp.max())
            ax2.set_ylim(xp.min()-.5, xp.max()+.5)
        
        ax2.invert_xaxis()

        if ax3.yaxis_inverted():
            ax2.invert_yaxis()

        ax2.axis('off')

    ## draw colorbar
    sca(ax3)
    cb = None
    if show_colorbar:
        if nrow > 1:
            axes = [ax1, ax2, ax3]
            while None in axes:
                axes.remove(None)
            s = H / (H + 1.)
            cb = colorbar(mappable=im, ax=axes, anchor=(0, 0), shrink=s, extend=cb_extend)
        else:
            cb = colorbar(mappable=im, extend=cb_extend)

    sca(ax3)
    sci(im)

    if interactive:
        from prody.utilities import ImageCursor
        from matplotlib.pyplot import connect
        cursor = ImageCursor(ax3, im)
        connect('button_press_event', cursor.onClick)

    ax3.tick_params(axis='x', rotation=xtickrotation)

    return im, lines, cb