Python matplotlib.ticker.FuncFormatter() Examples

The following are 30 code examples of matplotlib.ticker.FuncFormatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.ticker , or try the search function .
Example #1
Source File: explorers.py    From yass with Apache License 2.0 6 votes vote down vote up
def plot_series(self, from_time, to_time, channels='all', ax=None):
        """Plot observations in a selected number of channels
        """

        if channels == 'all':
            channels = range(self.n_channels)

        ax = ax if ax else plt

        f, axs = plt.subplots(len(channels), 1)

        formatter = FuncFormatter(lambda x, pos: from_time + int(x))

        for ax, ch in zip(axs, channels):
            ax.plot(self.reader[from_time:to_time, ch])
            ax.set_title('Channel {}'.format(ch), fontsize=25)
            ax.xaxis.set_major_formatter(formatter)
            ax.tick_params(axis='x', which='major', labelsize=25)

        plt.tight_layout() 
Example #2
Source File: cpug.py    From cpu-g with GNU General Public License v3.0 6 votes vote down vote up
def read_data_for_battery_plot(self):
        bd = BatteryDriver()
        data = bd.get_history_charge()
        x = []
        y = []
        for element in data:
            x.append(element[0])
            y.append(element[1])
        self.ax.cla()
        self.ax.set_xlim(min(x), max(x))
        self.ax.set_ylim(-10, 110)
        self.ax.grid(True)

        def format_date(x, pos=None):
            ltime = time.localtime(x)
            return time.strftime('%H:%M', ltime)

        self.ax.xaxis.set_major_formatter(
            ticker.FuncFormatter(format_date))
        self.fig.autofmt_xdate()
        self.ax.plot(x, y)
        self.fig.canvas.draw()
        return True 
Example #3
Source File: run.py    From themarketingtechnologist with Apache License 2.0 6 votes vote down vote up
def create_example_s_curve_plot(self):
        # Initialize plot
        fig, ax = plt.subplots(figsize=(8, 4))
        # Plot example S-response curve
        x = np.arange(0, 20100, 100)
        y = self.logistic_function(x, L=10000, k=0.0007, x_0=10000)
        ax.plot(x, y, '-', label="Radio")
        # Set plot options and show plot
        ax.legend(loc='right')
        plt.xlim([0, 20000])
        plt.xlabel('Radio spend in euros')
        plt.ylabel('Additional sales')
        plt.title('Example of S-shaped response curve')
        plt.tight_layout()
        plt.grid()
        ax.get_xaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))
        ax.get_yaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))
        plt.show() 
Example #4
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def wrap_formatter(formatter):
    """
    Wraps formatting function or string in
    appropriate matplotlib formatter type.
    """
    if isinstance(formatter, ticker.Formatter):
        return formatter
    elif callable(formatter):
        args = [arg for arg in _getargspec(formatter).args
                if arg != 'self']
        wrapped = formatter
        if len(args) == 1:
            def wrapped(val, pos=None):
                return formatter(val)
        return ticker.FuncFormatter(wrapped)
    elif isinstance(formatter, basestring):
        if re.findall(r"\{(\w+)\}", formatter):
            return ticker.StrMethodFormatter(formatter)
        else:
            return ticker.FormatStrFormatter(formatter) 
Example #5
Source File: base.py    From django-tree with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot(self, df, database_name, test_name, y_label):
        means = df.rolling(max(df.index.max() // 20, 1)).mean()
        ax = means.plot(
            title=test_name, alpha=0.8,
            xlim=(0, means.index.max() * 1.05),
            ylim=(0, means.max().max() * 1.05),
        )
        ax.set(xlabel='Amount of objects in table', ylabel=y_label)

        ax.xaxis.set_major_formatter(
            FuncFormatter(lambda v, pos: prefix_unit(v, '', -3)))
        if y_label in self.ticks_formatters:
            ax.yaxis.set_major_formatter(self.ticks_formatters[y_label])

        legend = ax.legend(
            loc='upper center', bbox_to_anchor=(0.5, 0.0),
            bbox_transform=plt.gcf().transFigure,
            fancybox=True, shadow=True, ncol=3)

        filename = ('%s - %s.svg' % (database_name,
                                     test_name)).replace(' ', '_')
        plt.savefig(
            os.path.join(self.results_path, filename),
            bbox_extra_artists=(legend,), bbox_inches='tight',
        ) 
Example #6
Source File: basic_units.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def axisinfo(unit, axis):
        'return AxisInfo instance for x and unit'

        if unit == radians:
            return units.AxisInfo(
                majloc=ticker.MultipleLocator(base=np.pi/2),
                majfmt=ticker.FuncFormatter(rad_fn),
                label=unit.fullname,
            )
        elif unit == degrees:
            return units.AxisInfo(
                majloc=ticker.AutoLocator(),
                majfmt=ticker.FormatStrFormatter(r'$%i^\circ$'),
                label=unit.fullname,
            )
        elif unit is not None:
            if hasattr(unit, 'fullname'):
                return units.AxisInfo(label=unit.fullname)
            elif hasattr(unit, 'unit'):
                return units.AxisInfo(label=unit.unit.fullname)
        return None 
Example #7
Source File: QAAnalysis_block.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def plot_index(self, methods='mv'):
        block_index=self.block_index('close')
        def format_date(x, pos=None):
            # 保证下标不越界,很重要,越界会导致最终plot坐标轴label无显示
            thisind = np.clip(int(x+0.5), 0, N-1)
            # print(thisind)
            return block_index.index[thisind].strftime('%Y-%m-%d %H:%M')
        fig = plt.figure(figsize=(14, 12))
        ax = fig.add_subplot(1, 1, 1)
        plt.style.use('ggplot')

        plt.title('QUANTAXIS BLOCK ANA {}'.format(
            self.name), fontproperties="SimHei")
        N = len(block_index)
        block_index.reset_index()[0].plot()
        self.block_index('lv').reset_index()[0].plot()
        self.block_index('close').reset_index()[0].plot()
        self.block_index('volume').reset_index()[0].plot()
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
        plt.legend(['market_value', 'liquidity_value', 'close', 'volume'])
        plt.show() 
Example #8
Source File: tearsheet.py    From qstrader with MIT License 6 votes vote down vote up
def _plot_yearly_returns(self, stats, ax=None, **kwargs):
        """
        Plots a barplot of returns by year.
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        returns = stats['returns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')

        yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0
        yly_ret.plot(ax=ax, kind="bar")
        ax.set_title('Yearly Returns (%)', fontweight='bold')
        ax.set_ylabel('')
        ax.set_xlabel('')
        ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
        ax.xaxis.grid(False)

        return ax 
Example #9
Source File: histogram.py    From time_trial with MIT License 6 votes vote down vote up
def add_plot(self, plot):
        ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*self.settings.x_scaling))
        self.axes.xaxis.set_major_formatter(ticks)

        if plot.minimum is None and plot.maximum is None:
            range = [min(plot.timing_data.data), max(plot.timing_data.data)]
        elif plot.range_type == "absolute":
            range = [plot.minimum, plot.maximum]
            print(range)
            if len(numpy.intersect1d(range, plot.timing_data.data)) == 0:
                msg = QtGui.QMessageBox()
                msg.setIcon(QtGui.QMessageBox.Warning)
                msg.setText("The specified range is invalid for data set as they do not overlap. Falling back to plotting the full range instead:\n [min(data), max(data)].")
                msg.exec()
                logging.warning("Specified range is invalid for data. Falling back to [min(data), max(data)].")
                plot.minimum = min(plot.timing_data.data)
                plot.maximum = max(plot.timing_data.data)
                range = [plot.minimum, plot.maximum]

        else:
            range = [plot.timing_data.quantile(plot.minimum), plot.timing_data.quantile(plot.maximum)]

        self.add_plot_raw(plot.timing_data.data, plot.bins, plot.style, range, plot.label, plot.color) 
Example #10
Source File: tearsheet.py    From qstrader with MIT License 6 votes vote down vote up
def _plot_yearly_returns(self, stats, ax=None, **kwargs):
        """
        Plots a barplot of returns by year.
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        returns = stats['returns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')

        yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0
        yly_ret.plot(ax=ax, kind="bar")
        ax.set_title('Yearly Returns (%)', fontweight='bold')
        ax.set_ylabel('')
        ax.set_xlabel('')
        ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
        ax.xaxis.grid(False)

        return ax 
Example #11
Source File: mplot.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def apply_format(self, fmtfct=lambda x: x):
        wrapper = lambda x, pos: fmtfct(x)
        self.axis.set_major_formatter(FuncFormatter(wrapper))
        return self 
Example #12
Source File: plotting.py    From lens with Apache License 2.0 5 votes vote down vote up
def _set_integer_tick_labels(axis, labels):
    """Use labels dict to set labels on axis"""
    axis.set_major_formatter(FuncFormatter(lambda x, _: labels.get(x, "")))
    axis.set_major_locator(MaxNLocator(integer=True)) 
Example #13
Source File: plot.py    From PyTorchWavelets with MIT License 5 votes vote down vote up
def plot_scalogram(power, scales, t, normalize_columns=True, cmap=None, ax=None, scale_legend=True):
    """
    Plot the wavelet power spectrum (scalogram).

    :param power: np.ndarray, CWT power spectrum of shape [n_scales,signal_length]
    :param scales: np.ndarray, scale distribution of shape [n_scales]
    :param t: np.ndarray, temporal range of shape [signal_length]
    :param normalize_columns: boolean, whether to normalize spectrum per timestep
    :param cmap: matplotlib cmap, please refer to their documentation
    :param ax: matplotlib axis object, if None creates a new subplot
    :param scale_legend: boolean, whether to include scale legend on the right
    :return: ax, matplotlib axis object that contains the scalogram
    """

    if not cmap: cmap = plt.get_cmap("PuBu_r")
    if ax is None: fig, ax = plt.subplots()
    if normalize_columns: power = power/np.max(power, axis=0)

    T, S = np.meshgrid(t, scales)
    cnt = ax.contourf(T, S, power, 100, cmap=cmap)

    # Fix for saving as PDF (aliasing)
    for c in cnt.collections:
        c.set_edgecolor("face")

    ax.set_yscale('log')
    ax.set_ylabel("Scale (Log Scale)")
    ax.set_xlabel("Time (s)")
    ax.set_title("Wavelet Power Spectrum")

    if scale_legend:
        def format_axes_label(x, pos):
            return "{:.2f}".format(x)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(cnt, cax=cax, ticks=[np.min(power), 0, np.max(power)],
                     format=ticker.FuncFormatter(format_axes_label))

    return ax 
Example #14
Source File: plots.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def _plot_trend(ax, x, q1, y, q3, xlim, ylim, ylabel, ytick_formatter):
    # compute the best-fit (linear) trend line
    fit = np.polyfit(x, y, 1)
    fit_fn = np.poly1d(fit)

    # plot the data, the trendlines, and the interquartile range (if given)
    ax.plot(x, y, color=TREND_LINE_COLOR)
    ax.plot(x, fit_fn(x), '--k', dashes=(1, 1), linewidth=0.75)
    if all(q1) and all(q3):
        ax.fill_between(x, q1, q3, facecolor=TREND_RANGE_COLOR, alpha=TREND_RANGE_ALPHA, linewidths=0)

    # x-axis settings
    ax.set_xlim(*xlim)
    ax.spines['top'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.xaxis.set_tick_params(labelsize=TICK_SIZE)
    ax.set_xlabel('Day of month', fontsize=AXIS_TITLE_SIZE)

    # y-axis settings
    ax.set_ylim(*ylim)
    ax.spines['right'].set_visible(False)
    ax.yaxis.set_ticks_position('left')
    ax.yaxis.set_tick_params(labelsize=TICK_SIZE)

    trend_yaxis_major_formatter, yaxis_magnitude = _trend_yaxis_major_formatter(ylim[-1], ytick_formatter)
    if yaxis_magnitude:
        ylabel += f'\n({yaxis_magnitude})'
    ax.set_ylabel(ylabel, fontsize=AXIS_TITLE_SIZE)
    ax.yaxis.set_major_formatter(FuncFormatter(trend_yaxis_major_formatter)) 
Example #15
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_equity(self, stats, ax=None, **kwargs):
        """
        Plots cumulative rolling returns versus some benchmark.
        """
        def format_two_dec(x, pos):
            return '%.2f' % x

        equity = stats['cum_returns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_two_dec)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.xaxis.set_tick_params(reset=True)
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        if self.benchmark is not None:
            benchmark = stats['cum_returns_b']
            benchmark.plot(
                lw=2, color='gray', label=self.benchmark, alpha=0.60,
                ax=ax, **kwargs
            )

        equity.plot(lw=2, color='green', alpha=0.6, x_compat=False,
                    label='Backtest', ax=ax, **kwargs)

        ax.axhline(1.0, linestyle='--', color='black', lw=1)
        ax.set_ylabel('Cumulative returns')
        ax.legend(loc='best')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')

        if self.log_scale:
            ax.set_yscale('log')

        return ax 
Example #16
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_rolling_sharpe(self, stats, ax=None, **kwargs):
        """
        Plots the curve of rolling Sharpe ratio.
        """
        def format_two_dec(x, pos):
            return '%.2f' % x

        sharpe = stats['rolling_sharpe']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_two_dec)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.xaxis.set_tick_params(reset=True)
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        if self.benchmark is not None:
            benchmark = stats['rolling_sharpe_b']
            benchmark.plot(
                lw=2, color='gray', label=self.benchmark, alpha=0.60,
                ax=ax, **kwargs
            )

        sharpe.plot(lw=2, color='green', alpha=0.6, x_compat=False,
                    label='Backtest', ax=ax, **kwargs)

        ax.axvline(sharpe.index[252], linestyle="dashed", c="gray", lw=2)
        ax.set_ylabel('Rolling Annualised Sharpe')
        ax.legend(loc='best')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')

        return ax 
Example #17
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_drawdown(self, stats, ax=None, **kwargs):
        """
        Plots the underwater curve
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        drawdown = stats['drawdowns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_tick_params(reset=True)
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        underwater = -100 * drawdown
        underwater.plot(ax=ax, lw=2, kind='area', color='red', alpha=0.3, **kwargs)
        ax.set_ylabel('')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')
        ax.set_title('Drawdown (%)', fontweight='bold')
        return ax 
Example #18
Source File: test_bbox_tight.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_bbox_inches_tight_suptile_legend():
    plt.plot(np.arange(10), label='a straight line')
    plt.legend(bbox_to_anchor=(0.9, 1), loc=2, )
    plt.title('Axis title')
    plt.suptitle('Figure title')

    # put an extra long y tick on to see that the bbox is accounted for
    def y_formatter(y, pos):
        if int(y) == 4:
            return 'The number 4'
        else:
            return str(y)
    plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))

    plt.xlabel('X axis') 
Example #19
Source File: explorers.py    From yass with Apache License 2.0 5 votes vote down vote up
def plot_waveform(self, time, channels, ax=None, line_at_t=False,
                      overlay=False):
        """
        Plot a waveform around a window size in selected channels
        """
        ax = ax if ax else plt

        n_channels = len(channels)
        formatter = FuncFormatter(lambda x, pos: time - self.spike_size +
                                  int(x))

        if overlay:
            axs = [ax] * n_channels
        else:
            f, axs = ax.subplots(n_channels, 1)

        for ch, ax in zip(channels, axs):
            waveform = self.read_waveform(time, ch)
            ax.plot(waveform)
            ax.set_title('Channel {}'.format(ch), fontsize=12)
            ax.xaxis.set_major_formatter(formatter)
            ax.tick_params(axis='x', which='major', labelsize=10)

            if line_at_t:
                ax.axvline(x=time)

        plt.tight_layout() 
Example #20
Source File: __init__.py    From trendln with MIT License 5 votes vote down vote up
def plot_sup_res_date(hist, idx, numbest = 2, fromwindows = True, pctbound=0.1,
                      extmethod = METHOD_NUMDIFF, method=METHOD_NSQUREDLOGN, window=125,
                      errpct = 0.005, hough_scale=0.01, hough_prob_iter=10, sortError=False, accuracy=1):
    import matplotlib.ticker as ticker
    return plot_support_resistance(hist, ticker.FuncFormatter(datefmt(idx)), numbest, fromwindows,
                                   pctbound, extmethod, method, window, errpct, hough_scale, hough_prob_iter, sortError, accuracy) 
Example #21
Source File: _numerical_integration.py    From respy with MIT License 5 votes vote down vote up
def set_formatter(ax, is_int=True, which="xy"):
    """Formats axis values.

    Input
        - ax: which ax object to format
        - which: axis

    Output
        - formatted ax object
    """
    formatter = ticker.FuncFormatter(lambda x, p: format(int(x), ","))
    if "x" in which:
        ax.get_xaxis().set_major_formatter(formatter)
    if "y" in which:
        ax.get_yaxis().set_major_formatter(formatter) 
Example #22
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_drawdown(self, stats, ax=None, **kwargs):
        """
        Plots the underwater curve
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        drawdown = stats['drawdowns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_tick_params(reset=True)
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        underwater = -100 * drawdown
        underwater.plot(ax=ax, lw=2, kind='area', color='red', alpha=0.3, **kwargs)
        ax.set_ylabel('')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')
        ax.set_title('Drawdown (%)', fontweight='bold')
        return ax 
Example #23
Source File: Plot.py    From Wave-U-Net with MIT License 5 votes vote down vote up
def draw_spectrogram(example_wav="musb_005_angela thomas wade_audio_model_without_context_cut_28234samples_61002samples_93770samples_126538.wav"):
    y, sr = Utils.load(example_wav, sr=None)
    spec = np.abs(librosa.stft(y, 512, 256, 512))
    norm_spec = librosa.power_to_db(spec**2)
    black_time_frames = np.array([28234, 61002, 93770, 126538]) / 256.0

    fig, ax = plt.subplots()
    img = ax.imshow(norm_spec)
    plt.vlines(black_time_frames, [0, 0, 0, 0], [10, 10, 10, 10], colors="red", lw=2, alpha=0.5)
    plt.vlines(black_time_frames, [256, 256, 256, 256], [246, 246, 246, 246], colors="red", lw=2, alpha=0.5)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    plt.colorbar(img, cax=cax)

    ax.xaxis.set_label_position("bottom")
    #ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x * 256.0 / sr))
    #ax.xaxis.set_major_formatter(ticks_x)
    ax.xaxis.set_major_locator(ticker.FixedLocator(([i * sr / 256. for i in range(len(y)//sr + 1)])))
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(([str(i) for i in range(len(y)//sr + 1)])))

    ax.yaxis.set_major_locator(ticker.FixedLocator(([float(i) * 2000.0 / (sr/2.0) * 256. for i in range(6)])))
    ax.yaxis.set_major_formatter(ticker.FixedFormatter([str(i*2) for i in range(6)]))

    ax.set_xlabel("t (s)")
    ax.set_ylabel('f (KHz)')

    fig.set_size_inches(7., 3.)
    fig.savefig("spectrogram_example.pdf", bbox_inches='tight') 
Example #24
Source File: mplot.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def millions(self, precision=1):
        fct = fmt.new_millions_formatter(precision=precision)
        wrapper = lambda x, pos: fct(x)
        self.axis.set_major_formatter(FuncFormatter(wrapper))
        return self 
Example #25
Source File: mplot.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def thousands(self, precision=1):
        fct = fmt.new_thousands_formatter(precision=precision)
        wrapper = lambda x, pos: fct(x)
        self.axis.set_major_formatter(FuncFormatter(wrapper))
        return self 
Example #26
Source File: mplot.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def percent(self, precision=2):
        fct = fmt.new_percent_formatter(precision=precision)
        wrapper = lambda x, pos: fct(x)
        self.axis.set_major_formatter(FuncFormatter(wrapper))
        return self 
Example #27
Source File: performance_plotter.py    From tornado with MIT License 5 votes vote down vote up
def plot_multi_ddms_points(pairs_names, d_lists, project_name, dir_path, file_name, color_set):

        num_subplots = len(pairs_names)

        fig = plt.figure(figsize=(10, 0.75 * num_subplots))

        for i in range(0, num_subplots):
            y = d_lists[i]
            x = []
            y_ = []
            for j in range(0, len(y)):
                if y[j] == 1:
                    x.append((j / len(y)) * 100)
                    y_.append(1)

            ax = plt.subplot(num_subplots, 1, i + 1)

            # LaTeX rendering case. You may use the next line if you have LaTeX installed.
            # ax.set_title(r'\textsc{' + project_name.title() + '}' + " vs.\ " + pairs_names[i],
            #             fontsize=14, loc='left')
            ax.set_title(project_name.title() + " vs. " + pairs_names[i], fontsize=14, loc='left')

            ax.scatter(x, y_, 30, edgecolors=color_set[i], color=color_set[i], label=pairs_names[i])
            ax.set_xlim(0, 100)
            ax.set_ylim(0.95, 1.05)

            # LaTeX rendering case. You may use the next line if you have LaTeX installed.
            # ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '\%'))
            ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '%'))

            ax.xaxis.set_tick_params(labelsize=9)
            if i < len(pairs_names) - 1:
                ax.set_xticklabels([])
            ax.yaxis.set_visible(False)

        plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)

        file_path = (dir_path + file_name + "_drifts").lower()

        fig.savefig(file_path + ".pdf", dpi=150, bbox_inches='tight')
        fig.savefig(file_path + ".png", dpi=150, bbox_inches='tight') 
Example #28
Source File: performance_plotter.py    From tornado with MIT License 5 votes vote down vote up
def plot_single_ddm_points(learner_name, drift_points, project_name, dir_path, file_name, colour="ORANGERED"):

        fig = plt.figure(figsize=(10, 0.75))

        y = drift_points
        x = []
        y_ = []
        for j in range(0, len(y)):
            if y[j] == 1:
                x.append((j / len(y)) * 100)
                y_.append(1)

        ax = plt.subplot(111)

        # LaTeX rendering case. You may use the next line if you have LaTeX installed.
        # ax.set_title(r'\textsc{' + project_name.title() + '}' + " vs.\ " + learner_name, fontsize=14, loc='left')
        ax.set_title(project_name.title() + " vs. " + learner_name, fontsize=14, loc='left')

        ax.scatter(x, y_, 30, edgecolors=colour, color=colour, label=learner_name)
        ax.set_xlim(0, 100)
        ax.set_ylim(0.95, 1.05)

        # LaTeX rendering case. You may use the next line if you have LaTeX installed.
        # ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '\%'))
        ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '%'))

        ax.xaxis.set_tick_params(labelsize=9)
        ax.yaxis.set_visible(False)

        file_path = (dir_path + file_name + "_drifts").lower()

        plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
        fig.savefig(file_path + ".pdf", dpi=150, bbox_inches='tight')
        fig.savefig(file_path + ".png", dpi=150, bbox_inches='tight') 
Example #29
Source File: rt-heatmap.py    From pyrocore with GNU General Public License v2.0 5 votes vote down vote up
def heatmap(self, df, imagefile):
        """ Create the heat map.
        """
        import seaborn as sns
        import matplotlib.ticker as tkr
        import matplotlib.pyplot as plt
        from  matplotlib.colors import LinearSegmentedColormap

        sns.set()
        with sns.axes_style('whitegrid'):
            fig, ax = plt.subplots(figsize=(5, 11))  # inches

            cmax = max(df[self.args[2]].max(), self.CMAP_MIN_MAX)
            csteps = {
                0.0: 'darkred', 0.3/cmax: 'red', 0.6/cmax: 'orangered', 0.9/cmax: 'coral',
                1.0/cmax: 'skyblue', 1.5/cmax: 'blue', 1.9/cmax: 'darkblue',
                2.0/cmax: 'darkgreen', 3.0/cmax: 'green',
                (self.CMAP_MIN_MAX - .1)/cmax: 'palegreen', 1.0: 'yellow'}
            cmap = LinearSegmentedColormap.from_list('RdGrYl', sorted(csteps.items()), N=256)

            dataset = df.pivot(*self.args)

            sns.heatmap(dataset, mask=dataset.isnull(), annot=False, linewidths=.5, square=True, ax=ax, cmap=cmap,
                        annot_kws=dict(stretch='condensed'))
            ax.tick_params(axis='y', labelrotation=30, labelsize=8)
            # ax.get_yaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: x))
            plt.savefig(imagefile) 
Example #30
Source File: performance_plotter.py    From tornado with MIT License 5 votes vote down vote up
def plot_single(learner_name, performance_array, y_title,
                    project_name, dir_path, file_name, y_lim, legend_loc, zip_size, colour="ORANGERED"):

        x = []
        y = []
        for i in range(0, len(performance_array)):
            if i % zip_size == 0 or i == len(performance_array) - 1:
                x.append((i / len(performance_array)) * 100)
                y.append(performance_array[i])

        fig = plt.figure()
        ax = fig.add_subplot(111)

        # LaTeX rendering case. You may use the next line if you have LaTeX installed.
        # ax.set_title(r'\textsc{' + project_name.title() + '}', fontsize=14)
        ax.set_title(project_name.title(), fontsize=14)

        ax.set_xlim(0, 100)
        if y_lim is not None:
            ax.set_ylim(y_lim[0], y_lim[1])
        ax.set_xlabel('Percentage of Instances', fontsize=14)
        ax.set_ylabel(y_title, fontsize=14)
        ax.grid()

        ax.plot(x, y, color=colour, linewidth=1.2, label=learner_name)

        leg = ax.legend(fontsize=14, loc=legend_loc, framealpha=0.9)
        for leg_obj in leg.legendHandles:
            leg_obj.set_linewidth(2.0)

        # LaTeX rendering case. You may use the next line if you have LaTeX installed.
        # ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '\%'))
        ax.xaxis.set_major_formatter(FuncFormatter(lambda ix, _: '%1.0f' % ix + '%'))

        file_path = (dir_path + file_name + "_" + y_title).lower()

        plt.tight_layout()
        plt.savefig(file_path + ".pdf", dpi=150)
        plt.savefig(file_path + ".png", dpi=150)