Python matplotlib.ticker.FormatStrFormatter() Examples

The following are 30 code examples of matplotlib.ticker.FormatStrFormatter(). 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: 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 #2
Source File: _tools.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #3
Source File: cem.py    From visual_dynamics with MIT License 6 votes vote down vote up
def visualization_init(self):
        fig = plt.figure(figsize=(12, 6), frameon=False, tight_layout=True)
        fig.canvas.set_window_title(self.servoing_pol.predictor.name)
        gs = gridspec.GridSpec(1, 2)
        plt.show(block=False)

        return_plotter = LossPlotter(fig, gs[0],
                                     format_dicts=[dict(linewidth=2)] * 2,
                                     labels=['mean returns / 10', 'mean discounted returns'],
                                     ylabel='returns')
        return_major_locator = MultipleLocator(1)
        return_major_formatter = FormatStrFormatter('%d')
        return_minor_locator = MultipleLocator(1)
        return_plotter._ax.xaxis.set_major_locator(return_major_locator)
        return_plotter._ax.xaxis.set_major_formatter(return_major_formatter)
        return_plotter._ax.xaxis.set_minor_locator(return_minor_locator)

        learning_plotter = LossPlotter(fig, gs[1], format_dicts=[dict(linewidth=2)] * 2, ylabel='mean evaluation values')
        return fig, return_plotter, learning_plotter 
Example #4
Source File: FranchiseAnimation.py    From FranchiseRevenueComparison with MIT License 6 votes vote down vote up
def init_graph(self):
        plt.title("Franchise Earnings Comparison Over 20 Years", transform=None, x=self.width*0.10, y=self.height*0.90, ha='left')
        if TRACK_FRANCHISES:
            plt.subplots_adjust(left=0.1, right=0.75, top=0.8, bottom=0.1)
        else:
            plt.subplots_adjust(left=0.1, right=0.9, top=0.8, bottom=0.1)
        yformat = ticker.FormatStrFormatter("$%2.1fB")
        self.ax = plt.gca()
        self.ax.yaxis.set_major_formatter(yformat)
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['bottom'].set_visible(False)
        self.ax.spines['left'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        for _ in self.franchise_data_array:
            line, = self.ax.step([], [], lw=1, where='post')
            self.lines.append(line)
        x_indent_2 = self.width*0.75
        y_indent_1 = self.height*0.88
        self.leaderboard['cur_date']    = self.ax.text(x_indent_2, y_indent_1, "", transform=None, fontsize=16, fontname='Monospace')
        self.ax.text(self.width*0.30, self.height*0.85, "(Adjusted for inflation)", transform=None, ha='left') 
Example #5
Source File: _tools.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #6
Source File: _tools.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #7
Source File: _tools.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #8
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 #9
Source File: _tools.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #10
Source File: 10d PSG (Plots Tabs and sin cos options).py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example #11
Source File: 10e PSG (Same Window).py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example #12
Source File: _tools.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #13
Source File: metrics.py    From TensorFlow_DCIGN with MIT License 6 votes vote down vote up
def plot_single_cross_section_line(data, select, subplot):
  data = data[:, select]
  # subplot.scatter(data[:, 0], data[:, 1], s=20, lw=0, edgecolors='none', alpha=1.0,
  # subplot.plot(data[:, 0], data[:, 1], data[:, 2], color='black', lw=1, alpha=0.4)

  d = data
  # subplot.plot(d[[-1, 0], 0], d[[-1, 0], 1], d[[-1, 0], 2], lw=1, alpha=0.8, color='red')
  # subplot.scatter(d[[-1, 0], 0], d[[-1, 0], 1], d[[-1, 0], 2], lw=10, alpha=0.3, marker=".", color='b')
  d = data
  subplot.plot(data[:, 0], data[:, 1], data[:, 2], color='black', lw=1, alpha=0.4)

  subplot.set_xlim([-0.01, 1.01])
  subplot.set_ylim([-0.01, 1.01])
  subplot.set_zlim([-0.01, 1.01])
  ticks = []
  subplot.xaxis.set_ticks(ticks)
  subplot.yaxis.set_ticks(ticks)
  subplot.zaxis.set_ticks(ticks)
  subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
  subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f')) 
Example #14
Source File: Results.py    From MicroGrids with European Union Public License 1.1 6 votes vote down vote up
def LDR(Time_Series):

    columns=['Consume diesel', 'Lost Load', 'Energy PV','Curtailment','Energy Diesel', 
             'Discharge energy from the Battery', 'Charge energy to the Battery', 
             'Energy_Demand',  'State_Of_Charge_Battery'  ]
    Sort_Values = Time_Series.sort('Energy_Demand', ascending=False)
    
    index_values = []
    
    for i in range(len(Time_Series)):
        index_values.append((i+1)/float(len(Time_Series))*100)
    
    Sort_Values = pd.DataFrame(Sort_Values.values/1000, columns=columns, index=index_values)
    
    plt.figure() 
    ax = Sort_Values['Energy_Demand'].plot(style='k-',linewidth=1)
    
    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)
    ax.xaxis.set_major_formatter(xticks)
    ax.set_ylabel('Load (kWh)')
    ax.set_xlabel('Percentage (%)')
    
    plt.savefig('Results/LDR.png', bbox_inches='tight')
    plt.show() 
Example #15
Source File: lagrange.py    From pyray with MIT License 6 votes vote down vote up
def three_d_grid():
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Make data.
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = (X**3 + Y**3)
    Z = R

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                        linewidth=0, antialiased=False)

    # Customize the z axis.
    #ax.set_zlim(-1.01, 1.01)
    #ax.zaxis.set_major_locator(LinearLocator(10))
    #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show() 
Example #16
Source File: deforme.py    From Image-Restoration with MIT License 6 votes vote down vote up
def plot_surface(x,y,z):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    # Customize the z axis.
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    if save_info:
        fig.tight_layout()
        fig.savefig('./gaussian'+ str(idx) + '.png')
    plt.show() 
Example #17
Source File: AllenCahn_contracting_circle_standard_integrators.py    From pySDC with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot_radius(xcoords, exact_radius, radii):

    fig, ax = plt.subplots()
    plt.plot(xcoords, exact_radius, color='k', linestyle='--', linewidth=1, label='exact')

    for type, radius in radii.items():
        plt.plot(xcoords, radius, linestyle='-', linewidth=2, label=type)

    ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
    ax.set_ylabel('radius')
    ax.set_xlabel('time')
    ax.grid()
    ax.legend(loc=3)
    fname = 'data/AC_contracting_circle_standard_integrators'
    plt.savefig('{}.pdf'.format(fname), rasterized=True, bbox_inches='tight')

    # plt.show() 
Example #18
Source File: _tools.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _remove_labels_from_axis(axis):
    for t in axis.get_majorticklabels():
        t.set_visible(False)

    try:
        # set_visible will not be effective if
        # minor axis has NullLocator and NullFormattor (default)
        import matplotlib.ticker as ticker
        if isinstance(axis.get_minor_locator(), ticker.NullLocator):
            axis.set_minor_locator(ticker.AutoLocator())
        if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
            axis.set_minor_formatter(ticker.FormatStrFormatter(''))
        for t in axis.get_minorticklabels():
            t.set_visible(False)
    except Exception:   # pragma no cover
        raise
    axis.get_label().set_visible(False) 
Example #19
Source File: run_reg_toy.py    From streaming_sparse_gp with Apache License 2.0 6 votes vote down vote up
def plot_model(model, ax, cur_x, cur_y, pred_x, seen_x=None, seen_y=None):
    mx, vx = model.predict_f(pred_x)
    Zopt = model.Z.value
    mu, Su = model.predict_f_full_cov(Zopt)
    if len(Su.shape) == 3:
        Su = Su[:, :, 0]
        vx = vx[:, 0]
    ax.plot(cur_x, cur_y, 'kx', mew=1, alpha=0.8)
    if seen_x is not None:
        ax.plot(seen_x, seen_y, 'kx', mew=1, alpha=0.2)
    ax.plot(pred_x, mx, 'b', lw=2)
    ax.fill_between(
        pred_x[:, 0], mx[:, 0] -  2*np.sqrt(vx), 
        mx[:, 0] +  2*np.sqrt(vx), 
        color='b', alpha=0.3)
    ax.plot(Zopt, mu, 'ro', mew=1)
    ax.set_ylim([-2.4, 2])
    ax.set_xlim([np.min(pred_x), np.max(pred_x)])
    plt.subplots_adjust(hspace = .08)
    ax.set_ylabel('y')
    ax.yaxis.set_ticks(np.arange(-2, 3, 1))
    ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
    return mu, Su, Zopt 
Example #20
Source File: 10e PSG (Same Window).py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example #21
Source File: 10d PSG (Plots Tabs and sin cos options).py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example #22
Source File: visualization.py    From TensorFlow_DCIGN with MIT License 6 votes vote down vote up
def _plot_single_cross_section(data, select, subplot):
  data = data[:, select]
  # subplot.scatter(data[:, 0], data[:, 1], s=20, lw=0, edgecolors='none', alpha=1.0,
  subplot.plot(data[:, 0], data[:, 1], color='black', lw=1, alpha=0.4)
  subplot.plot(data[[-1, 0], 0], data[[-1, 0], 1], lw=1, alpha=0.8, color='red')
  subplot.scatter(data[:, 0], data[:, 1], s=4, alpha=1.0, lw=0.5,
                  c=_build_radial_colors(len(data)),
                  marker=".",
                  cmap=plt.cm.Spectral)
  # data = np.vstack((data, np.asarray([data[0, :]])))
  # subplot.plot(data[:, 0], data[:, 1], alpha=0.4)

  subplot.set_xlabel('feature %d' % select[0], labelpad=-12)
  subplot.set_ylabel('feature %d' % select[1], labelpad=-12)
  subplot.set_xlim([-0.05, 1.05])
  subplot.set_ylim([-0.05, 1.05])
  subplot.xaxis.set_ticks([0, 1])
  subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
  subplot.yaxis.set_ticks([0, 1])
  subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f')) 
Example #23
Source File: metrics.py    From TensorFlow_DCIGN with MIT License 6 votes vote down vote up
def plot_single_cross_section_3d(data, select, subplot):
  data = data[:, select]
  # subplot.scatter(data[:, 0], data[:, 1], s=20, lw=0, edgecolors='none', alpha=1.0,
  # subplot.plot(data[:, 0], data[:, 1], data[:, 2], color='black', lw=1, alpha=0.4)

  d = data
  # subplot.plot(d[[-1, 0], 0], d[[-1, 0], 1], d[[-1, 0], 2], lw=1, alpha=0.8, color='red')
  # subplot.scatter(d[[-1, 0], 0], d[[-1, 0], 1], d[[-1, 0], 2], lw=10, alpha=0.3, marker=".", color='b')
  d = data
  subplot.scatter(d[:, 0], d[:, 1], d[:, 2], s=4, alpha=1.0, lw=0.5,
                  c=vis._build_radial_colors(len(d)),
                  marker=".",
                  cmap=plt.cm.hsv)
  subplot.plot(data[:, 0], data[:, 1], data[:, 2], color='black', lw=0.2, alpha=0.9)

  subplot.set_xlim([-0.01, 1.01])
  subplot.set_ylim([-0.01, 1.01])
  subplot.set_zlim([-0.01, 1.01])
  ticks = []
  subplot.xaxis.set_ticks(ticks)
  subplot.yaxis.set_ticks(ticks)
  subplot.zaxis.set_ticks(ticks)
  subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
  subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f')) 
Example #24
Source File: tools.py    From L2L with GNU General Public License v3.0 5 votes vote down vote up
def plot(fn, random_state):
    """
    Implements plotting of 2D functions generated by FunctionGenerator
    :param fn: Instance of FunctionGenerator
    """
    import numpy as np
    from l2l.matplotlib_ import plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    fig = plt.figure()
    ax = fig.gca(projection=Axes3D.name)

    # Make data.
    X = np.arange(fn.bound[0], fn.bound[1], 0.05)
    Y = np.arange(fn.bound[0], fn.bound[1], 0.05)
    XX, YY = np.meshgrid(X, Y)
    Z = [fn.cost_function([x, y], random_state=random_state) for x, y in zip(XX.ravel(), YY.ravel())]
    Z = np.array(Z).reshape(XX.shape)

    # Plot the surface.
    surf = ax.plot_surface(XX, YY, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

    # Customize the z axis.
    # ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    W = np.where(Z == np.min(Z))
    ax.set(title='Min value is %.2f at (%.2f, %.2f)' % (np.min(Z), X[W[0]], Y[W[1]]))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.savefig('function.png')
    plt.show() 
Example #25
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_basic(self):
        # test % style formatter
        tmp_form = mticker.FormatStrFormatter('%05d')
        assert '00002' == tmp_form(2) 
Example #26
Source File: testelementplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_element_yformatter_string(self):
        curve = Curve(range(10)).options(yformatter='%d')
        plot = mpl_renderer.get_plot(curve)
        yaxis = plot.handles['axis'].yaxis
        yformatter = yaxis.get_major_formatter()
        self.assertIsInstance(yformatter, FormatStrFormatter)
        self.assertEqual(yformatter.fmt, '%d') 
Example #27
Source File: testelementplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_element_xformatter_string(self):
        curve = Curve(range(10)).options(xformatter='%d')
        plot = mpl_renderer.get_plot(curve)
        xaxis = plot.handles['axis'].xaxis
        xformatter = xaxis.get_major_formatter()
        self.assertIsInstance(xformatter, FormatStrFormatter)
        self.assertEqual(xformatter.fmt, '%d') 
Example #28
Source File: Map.py    From PyMICAPS with GNU General Public License v2.0 5 votes vote down vote up
def DrawGridLine(products, m):
        pj = products.map.projection
        if m is plt:
            # 坐标轴
            plt.axis(pj.axis)

            # 设置坐标轴刻度值显示格式
            if pj.axis == 'on':
                x_majorFormatter = FormatStrFormatter(pj.axisfmt[0])
                y_majorFormatter = FormatStrFormatter(pj.axisfmt[1])
                plt.gca().xaxis.set_major_formatter(x_majorFormatter)
                plt.gca().yaxis.set_major_formatter(y_majorFormatter)
                xaxis = plt.gca().xaxis
                for label in xaxis.get_ticklabels():
                    label.set_fontproperties('DejaVu Sans')
                    label.set_fontsize(10)
                yaxis = plt.gca().yaxis
                for label in yaxis.get_ticklabels():
                    label.set_fontproperties('DejaVu Sans')
                    label.set_fontsize(10)

                xaxis.set_visible(pj.lonlabels[3] == 1)
                yaxis.set_visible(pj.latlabels[0] == 1)

            return
        else:
            # draw parallels and meridians.
            if pj.axis == 'on':
                m.drawparallels(np.arange(-80., 81., 10.), labels=pj.latlabels, family='DejaVu Sans', fontsize=10)
                m.drawmeridians(np.arange(-180., 181., 10.), labels=pj.lonlabels, family='DejaVu Sans', fontsize=10) 
Example #29
Source File: animation_funcs.py    From FranchiseRevenueComparison with MIT License 5 votes vote down vote up
def create_animation_from_db(db):
    my_dpi = 150
    # fig = plt.figure(figsize=(1920/my_dpi, 1080/my_dpi), dpi=my_dpi)
    fig = plt.figure(figsize=(1080/my_dpi, 720/my_dpi), dpi=my_dpi)
    # fig = plt.figure()
    plt.title("Franchise Earnings Comparison Over 20 Years")
    frame_dates = create_date_array_for_animation(db)
    yformat = ticker.FormatStrFormatter("$%2.1fB")
    ax = plt.gca()
    ax.yaxis.set_major_formatter(yformat)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    lines = []
    handles = []
    franchise_text_array = []
    my_bbox = dict(boxstyle="round")
    for _ in db:
        line, = ax.step([], [], lw=1, where='post')
        lines.append(line)
        handles.append(line)
        franchise_date_pointer_array.append(0)
        # franchise_text_array.append(ax.text(0, 0, "Oops", rotation=-45, horizontalalignment='center'))
        # franchise_text_array.append(ax.text(0, 0, "", horizontalalignment='center', fontsize=6, bbox=my_bbox))
        franchise_text_array.append(ax.text(0, 0, "", horizontalalignment='center', fontsize=6))
    plt.legend(handles, [x.franchise_name for x in db], loc='upper left', fontsize=6)
    print("There are %s dates in frame_dates array" % len(frame_dates))
    animation_time = len(frame_dates)/30
    print("Which will make a video %.2f seconds long" % animation_time)
    anim = animation.FuncAnimation(fig,
                                   animate_multiple,
                                   fargs=(ax, db, lines, frame_dates, franchise_text_array),
                                   frames=int(len(frame_dates[:])*1.2), interval=0.01, blit=True)
    # anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
    plt.show() 
Example #30
Source File: testelementplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_element_zformatter_string(self):
        curve = Scatter3D([]).options(zformatter='%d')
        plot = mpl_renderer.get_plot(curve)
        zaxis = plot.handles['axis'].zaxis
        zformatter = zaxis.get_major_formatter()
        self.assertIsInstance(zformatter, FormatStrFormatter)
        self.assertEqual(zformatter.fmt, '%d')