Python matplotlib.ticker.ScalarFormatter() Examples

The following are 30 code examples of matplotlib.ticker.ScalarFormatter(). 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: dialog_timeline.py    From RF-Monitor with GNU General Public License v2.0 6 votes vote down vote up
def __setup_plot(self):
        figure = Figure(facecolor='lightgrey')

        self._axes = figure.add_subplot(111)
        self._axes.set_title('Timeline')
        self._axes.set_xlabel('Time')
        self._axes.set_ylabel('Frequency (MHz)')
        self._axes.grid(True)

        locator = AutoDateLocator()
        formatter = AutoDateFormatter(locator)
        self._axes.xaxis.set_major_formatter(formatter)
        self._axes.xaxis.set_major_locator(locator)
        formatter = ScalarFormatter(useOffset=False)
        self._axes.yaxis.set_major_formatter(formatter)
        self._axes.yaxis.set_minor_locator(AutoMinorLocator(10))

        self._canvas = FigureCanvas(self._panelPlot, -1, figure)
        self._canvas.mpl_connect('motion_notify_event', self.__on_motion)

        Legend.__init__(self, self._axes, self._canvas) 
Example #2
Source File: plot.py    From icepack with GNU General Public License v3.0 6 votes vote down vote up
def subplots(*args, **kwargs):
    subplot_kw = kwargs.get('subplot_kw', {})
    subplot_kw['adjustable'] = subplot_kw.get('adjustable', 'box')
    kwargs['subplot_kw'] = subplot_kw
    fig, axes = plt.subplots(*args, **kwargs)

    def fmt(ax):
        ax.set_aspect('equal')
        ax.xaxis.set_major_formatter(ScalarFormatter(useOffset=True))
        ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=True))
        ax.xaxis.get_major_formatter().set_powerlimits((0, 0))
        ax.yaxis.get_major_formatter().set_powerlimits((0, 0))

    try:
        for ax in axes:
            fmt(ax)
    except TypeError:
        fmt(axes)

    return fig, axes 
Example #3
Source File: UnitDblFormatter.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__( self, *args, **kwargs ):
      'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
      ticker.ScalarFormatter.__init__( self, *args, **kwargs ) 
Example #4
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_use_offset(self, use_offset):
        with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}):
            tmp_form = mticker.ScalarFormatter()
            assert use_offset == tmp_form.get_useOffset() 
Example #5
Source File: grid_finder.py    From CogAlg with MIT License 5 votes vote down vote up
def __init__(self, useMathText=True):
        self._fmt = mticker.ScalarFormatter(
            useMathText=useMathText, useOffset=False)
        self._fmt.create_dummy_axis()
        self._ignore_factor = True 
Example #6
Source File: UnitDblFormatter.py    From CogAlg with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
        ticker.ScalarFormatter.__init__(self, *args, **kwargs) 
Example #7
Source File: UnitDblFormatter.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
        ticker.ScalarFormatter.__init__(self, *args, **kwargs) 
Example #8
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_scilimits(self, sci_type, scilimits, lim, orderOfMag):
        tmp_form = mticker.ScalarFormatter()
        tmp_form.set_scientific(sci_type)
        tmp_form.set_powerlimits(scilimits)
        fig, ax = plt.subplots()
        ax.yaxis.set_major_formatter(tmp_form)
        ax.set_ylim(*lim)
        tmp_form.set_locs(ax.yaxis.get_majorticklocs())
        assert orderOfMag == tmp_form.orderOfMagnitude 
Example #9
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_use_offset(self, use_offset):
        with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}):
            tmp_form = mticker.ScalarFormatter()
            assert use_offset == tmp_form.get_useOffset() 
Example #10
Source File: plotting.py    From jqfactor_analyzer with MIT License 5 votes vote down vote up
def plot_cumulative_returns_by_quantile(
    quantile_returns, period=1, overlap=True, ax=None
):

    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(18, 6))

    ret_wide = quantile_returns.reset_index()\
        .pivot(index='date', columns='factor_quantile',
               values=convert_to_forward_returns_columns(period))

    overlapping_period = period if overlap else 1
    cum_ret = ret_wide.apply(cumulative_returns, args=(overlapping_period,))
    cum_ret = cum_ret.loc[:, ::-1]

    cum_ret.plot(lw=2, ax=ax, cmap=cm.RdYlGn_r)
    ax.legend()
    ymin, ymax = cum_ret.min().min(), cum_ret.max().max()
    ax.set(
        ylabel=CUMRETQ.get("YLABEL"),
        title=CUMRETQ.get("TITLE").format(period),
        xlabel='',
        ylim=(ymin, ymax)
    )
    ax.set_yscale('symlog', linthreshy=1)
    ax.set_yticks(np.linspace(ymin, ymax, 8))
    ax.yaxis.set_major_formatter(ScalarFormatter())
    ax.axhline(1.0, linestyle='-', color='black', lw=1)

    return ax 
Example #11
Source File: labeled_example_plotter.py    From speechless with MIT License 5 votes vote down vote up
def prepare_spectrogram_plot(self, type: SpectrogramType = SpectrogramType.power_level,
                                 frequency_scale: SpectrogramFrequencyScale = SpectrogramFrequencyScale.linear) -> None:
        spectrogram = self.example.spectrogram(type, frequency_scale=frequency_scale)

        figure, axes = plt.subplots(1, 1)
        use_mel = frequency_scale == SpectrogramFrequencyScale.mel

        plt.title("\n".join(wrap(
            "{0}{1} spectrogram for {2}".format(("mel " if use_mel else ""), type.value, str(self)), width=100)))
        plt.xlabel("time (data every {}ms)".format(round(1000 / self.example.time_step_rate())))
        plt.ylabel("frequency (data evenly distributed on {} scale, {} total)".format(
            frequency_scale.value, self.example.frequency_count_from_spectrogram(spectrogram)))
        mel_frequencies = self.example.mel_frequencies()
        plt.imshow(
            spectrogram, cmap='gist_heat', origin='lower', aspect='auto', extent=
            [0, self.example.duration_in_s,
             librosa.hz_to_mel(mel_frequencies[0])[0] if use_mel else 0,
             librosa.hz_to_mel(mel_frequencies[-1])[0] if use_mel else self.example.highest_detectable_frequency()])

        plt.colorbar(label="{} ({})".format(
            type.value,
            "in{} dB, not aligned to a particular base level".format(" something similar to" if use_mel else "") if
            type == SpectrogramType.power_level else "only proportional to physical scale"))

        class ScalarFormatterWithUnit(ScalarFormatter):
            def __init__(self, unit: str):
                super().__init__()
                self.unit = unit

            def __call__(self, x, pos=None) -> str:
                return super().__call__(x, pos) + self.unit

        axes.xaxis.set_major_formatter(ScalarFormatterWithUnit("s"))
        axes.yaxis.set_major_formatter(
            FuncFormatter(lambda value, pos: "{}mel = {}Hz".format(int(value), int(
                librosa.mel_to_hz(value)[0]))) if use_mel else ScalarFormatterWithUnit("Hz"))
        figure.set_size_inches(19.20, 10.80) 
Example #12
Source File: test_ticker.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_use_offset():
    for use_offset in [True, False]:
        with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}):
            tmp_form = mticker.ScalarFormatter()
            nose.tools.assert_equal(use_offset, tmp_form.get_useOffset()) 
Example #13
Source File: axis.py    From ImageFusion with MIT License 5 votes vote down vote up
def cla(self):
        'clear the current axis'
        self.set_major_locator(mticker.AutoLocator())
        self.set_major_formatter(mticker.ScalarFormatter())
        self.set_minor_locator(mticker.NullLocator())
        self.set_minor_formatter(mticker.NullFormatter())

        self.set_label_text('')
        self._set_artist_props(self.label)

        # Keep track of setting to the default value, this allows use to know
        # if any of the following values is explicitly set by the user, so as
        # to not overwrite their settings with any of our 'auto' settings.
        self.isDefault_majloc = True
        self.isDefault_minloc = True
        self.isDefault_majfmt = True
        self.isDefault_minfmt = True
        self.isDefault_label = True

        # Clear the callback registry for this axis, or it may "leak"
        self.callbacks = cbook.CallbackRegistry()

        # whether the grids are on
        self._gridOnMajor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','major'))
        self._gridOnMinor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','minor'))

        self.label.set_text('')
        self._set_artist_props(self.label)

        self.reset_ticks()

        self.converter = None
        self.units = None
        self.set_units(None) 
Example #14
Source File: plot_stab_vs_k.py    From pySDC with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_stab_vs_k(slow_resolved, mvals, kvals, stabval):
    """
    Plotting routine for moduli

    Args:
        slow_resolved (bool): switch for lambda_slow
        mvals (numpy.ndarray): number of nodes
        kvals (numpy.ndarray): number of iterations
        stabval (numpy.ndarray): moduli
    """

    rcParams['figure.figsize'] = 2.5, 2.5
    fig = plt.figure()
    fs = 8
    plt.plot(kvals, stabval[0, :], 'o-', color='b', label=("M=%2i" % mvals[0]), markersize=fs - 2)
    plt.plot(kvals, stabval[1, :], 's-', color='r', label=("M=%2i" % mvals[1]), markersize=fs - 2)
    plt.plot(kvals, stabval[2, :], 'd-', color='g', label=("M=%2i" % mvals[2]), markersize=fs - 2)
    plt.plot(kvals, 1.0 + 0.0 * kvals, '--', color='k')
    plt.xlabel('Number of iterations K', fontsize=fs)
    plt.ylabel(r'Modulus of stability function $\left| R \right|$', fontsize=fs)
    plt.ylim([0.0, 1.2])
    if slow_resolved:
        plt.legend(loc='upper right', fontsize=fs, prop={'size': fs})
    else:
        plt.legend(loc='lower left', fontsize=fs, prop={'size': fs})

    plt.gca().get_xaxis().get_major_formatter().labelOnlyBase = False
    plt.gca().get_xaxis().set_major_formatter(ScalarFormatter())
    # plt.show()
    if slow_resolved:
        filename = 'data/stab_vs_k_resolved.png'
    else:
        filename = 'data/stab_vs_k_unresolved.png'

    fig.savefig(filename, bbox_inches='tight') 
Example #15
Source File: plotting.py    From beat with GNU General Public License v3.0 5 votes vote down vote up
def scale_axes(axis, scale, offset=0.):
    from matplotlib.ticker import ScalarFormatter

    class FormatScaled(ScalarFormatter):

        @staticmethod
        def __call__(value, pos):
            return '{:,.1f}'.format(offset + value * scale).replace(',', ' ')

    axis.set_major_formatter(FormatScaled()) 
Example #16
Source File: grid_finder.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, useMathText=True):
        self._fmt = mticker.ScalarFormatter(
            useMathText=useMathText, useOffset=False)
        self._fmt.create_dummy_axis()
        self._ignore_factor = True 
Example #17
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scilimits(self, sci_type, scilimits, lim, orderOfMag):
        tmp_form = mticker.ScalarFormatter()
        tmp_form.set_scientific(sci_type)
        tmp_form.set_powerlimits(scilimits)
        fig, ax = plt.subplots()
        ax.yaxis.set_major_formatter(tmp_form)
        ax.set_ylim(*lim)
        tmp_form.set_locs(ax.yaxis.get_majorticklocs())
        assert orderOfMag == tmp_form.orderOfMagnitude 
Example #18
Source File: plot_process_info.py    From benchmarks with Apache License 2.0 5 votes vote down vote up
def visualize(file_path):

  entries = []
  with open(file_path) as f:
    entries = [json.loads(line) for line in f.readlines() if line.strip()]

  if not entries:
    print('There is no data in file {}'.format(file_path))
    return

  pdf = backend_pdf.PdfPages("process_info.pdf")
  idx = 0
  names = [name for name in entries[0].keys() if name != 'time']
  times = [entry['time'] for entry in entries]

  for name in names:
    values = [entry[name] for entry in entries]
    fig = plt.figure()
    ax = plt.gca()
    ax.yaxis.set_major_formatter(tick.ScalarFormatter(useMathText=True))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,3))
    plt.plot(times, values, colors[idx % len(colors)], marker='x', label=name)
    plt.xlabel('Time (sec)')
    plt.ylabel(name)
    plt.ylim(ymin=0)
    plt.legend(loc = 'upper left')
    pdf.savefig(fig)
    idx += 1

  plt.show()
  pdf.close()
  print('Generated process_info.pdf from {}'.format(file_path)) 
Example #19
Source File: plot.py    From pde-surrogate with MIT License 5 votes vote down vote up
def plot_row(arrs, save_dir, filename, same_range=False, plot_fn='imshow', 
    cmap='viridis'):
    """
    Args:
        arrs (sequence of 2D Tensor or Numpy): seq of arrs to be plotted
        save_dir (str):
        filename (str):
        same_range (bool): if True, subplots have the same range (colorbar)
        plot_fn (str): choices=['imshow', 'contourf']
    """
    interpolation = None
    arrs = [to_numpy(arr) for arr in arrs]

    if same_range:
        vmax = max([np.amax(arr) for arr in arrs])
        vmin = min([np.amin(arr) for arr in arrs])
    else:
        vmax, vmin = None, None

    fig, _ = plt.subplots(1, len(arrs), figsize=(4.4 * len(arrs), 4))
    for i, ax in enumerate(fig.axes):
        if plot_fn == 'imshow':
            cax = ax.imshow(arrs[i], cmap=cmap, interpolation=interpolation,
                            vmin=vmin, vmax=vmax)
        elif plot_fn == 'contourf':
            cax = ax.contourf(arrs[i], 50, cmap=cmap, vmin=vmin, vmax=vmax)
        if plot_fn == 'contourf':
            for c in cax.collections:
                c.set_edgecolor("face")
                c.set_linewidth(0.000000000001)
        ax.set_axis_off()
        cbar = plt.colorbar(cax, ax=ax, fraction=0.046, pad=0.04,
                            format=ticker.ScalarFormatter(useMathText=True))
        cbar.formatter.set_powerlimits((-2, 2))
        cbar.ax.yaxis.set_offset_position('left')
        # cbar.ax.tick_params(labelsize=5)
        cbar.update_ticks()
    plt.tight_layout(pad=0.05, w_pad=0.05, h_pad=0.05)
    plt.savefig(save_dir + f'/{filename}.{ext}', dpi=dpi, bbox_inches='tight')
    plt.close(fig) 
Example #20
Source File: axis.py    From Computable with MIT License 5 votes vote down vote up
def cla(self):
        'clear the current axis'
        self.set_major_locator(mticker.AutoLocator())
        self.set_major_formatter(mticker.ScalarFormatter())
        self.set_minor_locator(mticker.NullLocator())
        self.set_minor_formatter(mticker.NullFormatter())

        self.set_label_text('')
        self._set_artist_props(self.label)

        # Keep track of setting to the default value, this allows use to know
        # if any of the following values is explicitly set by the user, so as
        # to not overwrite their settings with any of our 'auto' settings.
        self.isDefault_majloc = True
        self.isDefault_minloc = True
        self.isDefault_majfmt = True
        self.isDefault_minfmt = True
        self.isDefault_label = True

        # Clear the callback registry for this axis, or it may "leak"
        self.callbacks = cbook.CallbackRegistry()

        # whether the grids are on
        self._gridOnMajor = rcParams['axes.grid']
        self._gridOnMinor = False

        self.label.set_text('')
        self._set_artist_props(self.label)

        self.reset_ticks()

        self.converter = None
        self.units = None
        self.set_units(None) 
Example #21
Source File: grid_finder.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self, useMathText=True):
        self._fmt = mticker.ScalarFormatter(useMathText=useMathText, useOffset=False)
        self._fmt.create_dummy_axis()
        self._ignore_factor = True 
Example #22
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def cla(self):
        'clear the current axis'
        self.set_major_locator(mticker.AutoLocator())
        self.set_major_formatter(mticker.ScalarFormatter())
        self.set_minor_locator(mticker.NullLocator())
        self.set_minor_formatter(mticker.NullFormatter())

        self.set_label_text('')
        self._set_artist_props(self.label)

        # Keep track of setting to the default value, this allows use to know
        # if any of the following values is explicitly set by the user, so as
        # to not overwrite their settings with any of our 'auto' settings.
        self.isDefault_majloc = True
        self.isDefault_minloc = True
        self.isDefault_majfmt = True
        self.isDefault_minfmt = True
        self.isDefault_label = True

        # Clear the callback registry for this axis, or it may "leak"
        self.callbacks = cbook.CallbackRegistry()

        # whether the grids are on
        self._gridOnMajor = rcParams['axes.grid']
        self._gridOnMinor = False

        self.label.set_text('')
        self._set_artist_props(self.label)

        self.reset_ticks()

        self.converter = None
        self.units = None
        self.set_units(None) 
Example #23
Source File: UnitDblFormatter.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__( self, *args, **kwargs ):
      'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
      ticker.ScalarFormatter.__init__( self, *args, **kwargs ) 
Example #24
Source File: grid_finder.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, useMathText=True):
        self._fmt = mticker.ScalarFormatter(useMathText=useMathText, useOffset=False)
        self._fmt.create_dummy_axis()
        self._ignore_factor = True 
Example #25
Source File: axis.py    From neural-network-animation with MIT License 5 votes vote down vote up
def cla(self):
        'clear the current axis'
        self.set_major_locator(mticker.AutoLocator())
        self.set_major_formatter(mticker.ScalarFormatter())
        self.set_minor_locator(mticker.NullLocator())
        self.set_minor_formatter(mticker.NullFormatter())

        self.set_label_text('')
        self._set_artist_props(self.label)

        # Keep track of setting to the default value, this allows use to know
        # if any of the following values is explicitly set by the user, so as
        # to not overwrite their settings with any of our 'auto' settings.
        self.isDefault_majloc = True
        self.isDefault_minloc = True
        self.isDefault_majfmt = True
        self.isDefault_minfmt = True
        self.isDefault_label = True

        # Clear the callback registry for this axis, or it may "leak"
        self.callbacks = cbook.CallbackRegistry()

        # whether the grids are on
        self._gridOnMajor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','major'))
        self._gridOnMinor = rcParams['axes.grid'] and (rcParams['axes.grid.which'] in ('both','minor'))

        self.label.set_text('')
        self._set_artist_props(self.label)

        self.reset_ticks()

        self.converter = None
        self.units = None
        self.set_units(None) 
Example #26
Source File: test_ticker.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_use_offset():
    for use_offset in [True, False]:
        with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}):
            tmp_form = mticker.ScalarFormatter()
            nose.tools.assert_equal(use_offset, tmp_form.get_useOffset()) 
Example #27
Source File: UnitDblFormatter.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__( self, *args, **kwargs ):
      'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
      ticker.ScalarFormatter.__init__( self, *args, **kwargs ) 
Example #28
Source File: UnitDblFormatter.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        'The arguments are identical to matplotlib.ticker.ScalarFormatter.'
        ticker.ScalarFormatter.__init__(self, *args, **kwargs) 
Example #29
Source File: grid_finder.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, useMathText=True):
        self._fmt = mticker.ScalarFormatter(
            useMathText=useMathText, useOffset=False)
        self._fmt.create_dummy_axis()
        self._ignore_factor = True 
Example #30
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_offset(self, use_offset):
        with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}):
            tmp_form = mticker.ScalarFormatter()
            assert use_offset == tmp_form.get_useOffset()