Python matplotlib.colorbar() Examples

The following are 30 code examples for showing how to use matplotlib.colorbar(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: defragTrees   Author: sato9hara   File: paper_synthetic2.py    License: MIT License 6 votes vote down vote up
def plotTZ(filename=None):
    t = np.linspace(0, 1, 101)
    z = 0.25 + 0.5 / (1 + np.exp(- 20 * (t - 0.5))) + 0.05 * np.cos(t * 2 * np.pi)
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    poly1 = [[0, 0]]
    poly1.extend([[t[i], z[i]] for i in range(t.size)])
    poly1.extend([[1, 0], [0, 0]])
    poly2 = [[0, 1]]
    poly2.extend([[t[i], z[i]] for i in range(t.size)])
    poly2.extend([[1, 1], [0, 1]])
    poly1 = plt.Polygon(poly1,fc=cmap(0.0))
    poly2 = plt.Polygon(poly2,fc=cmap(1.0))
    ax1.add_patch(poly1)
    ax1.add_patch(poly2)
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('True Data', size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Output y', size=22)
    plt.show()
    if not filename is None:
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 2
Project: defragTrees   Author: sato9hara   File: paper_synthetic1.py    License: MIT License 6 votes vote down vote up
def plotTZ(filename=None):
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    ax1.add_patch(pl.Rectangle(xy=[0, 0], width=0.5, height=0.5, facecolor=cmap(0.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0.5, 0.5], width=0.5, height=0.5, facecolor=cmap(0.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0, 0.5], width=0.5, height=0.5, facecolor=cmap(1.0), linewidth='2.0'))
    ax1.add_patch(pl.Rectangle(xy=[0.5, 0], width=0.5, height=0.5, facecolor=cmap(1.0), linewidth='2.0'))
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('True Data', size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Output y', size=22)
    plt.show()
    if not filename is None:
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 3
Project: scanpy   Author: theislab   File: _baseplot_class.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _plot_colorbar(self, color_legend_ax: Axes, normalize):
        """
        Plots a horizontal colorbar given the ax an normalize values

        Parameters
        ----------
        color_legend_ax
        normalize

        Returns
        -------
        None, updates color_legend_ax

        """
        cmap = pl.get_cmap(self.cmap)
        import matplotlib.colorbar

        matplotlib.colorbar.ColorbarBase(
            color_legend_ax, orientation='horizontal', cmap=cmap, norm=normalize
        )

        color_legend_ax.set_title(self.color_legend_title, fontsize='small')

        color_legend_ax.xaxis.set_tick_params(labelsize='small') 
Example 4
Project: defragTrees   Author: sato9hara   File: RulePlotter.py    License: MIT License 5 votes vote down vote up
def plotRule(mdl, X, d1, d2, alpha=0.8, filename='', rnum=-1, plot_line=[]):
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    if rnum <= 0:
        rnum = len(mdl.rule_)
    else:
        rnum = min(len(mdl.rule_), rnum)
    idx = np.argsort(mdl.weight_[:rnum])
    for i in range(rnum):
        r = mdl.rule_[idx[i]]
        box, vmin, vmax = __r2boxWithX(r, X)
        if mdl.modeltype_ == 'regression':
            c = cmap(mdl.pred_[idx[i]])
        elif mdl.modeltype_ == 'classification':
            r = mdl.pred_[idx[i]] / max(np.unique(mdl.pred_).size - 1, 1)
            c = cmap(r)
        ax1.add_patch(pl.Rectangle(xy=[box[0, d1], box[0, d2]], width=(box[1, d1] - box[0, d1]), height=(box[1, d2] - box[0, d2]), facecolor=c, linewidth='2.0', alpha=alpha))
    if len(plot_line) > 0:
        for l in plot_line:
            ax1.plot(l[0], l[1], 'k--')
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('Simplified Model (K = %d)' % (rnum,), size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Predictor y', size=22)
    plt.show()
    if not filename == '':
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 5
Project: defragTrees   Author: sato9hara   File: RulePlotter.py    License: MIT License 5 votes vote down vote up
def plotEachRule(mdl, X, d1, d2, alpha=0.8, filename='', rnum=-1, plot_line=[]):
    if rnum <= 0:
        rnum = len(mdl.rule_)
    else:
        rnum = min(len(mdl.rule_), rnum)
    m = rnum // 4
    if m * 4 < rnum:
        m += 1
    cmap = cm.get_cmap('cool')
    fig, ax = plt.subplots(m, 4 + 1, figsize=(4 * 4, 3 * m), gridspec_kw = {'width_ratios':[15, 15, 15, 15, 1]})
    idx = np.argsort(mdl.weight_[:rnum])
    for i in range(rnum):
        j = i // 4
        k = i - 4 * j
        r = mdl.rule_[idx[i]]
        box, vmin, vmax = __r2boxWithX(r, X)
        if mdl.modeltype_ == 'regression':
            c = cmap(mdl.pred_[idx[i]])
        elif mdl.modeltype_ == 'classification':
            r = mdl.pred_[idx[i]] / max(np.unique(mdl.pred_).size - 1, 1)
            c = cmap(r)
        ax[j, k].add_patch(pl.Rectangle(xy=[box[0, d1], box[0, d2]], width=(box[1, d1] - box[0, d1]), height=(box[1, d2] - box[0, d2]), facecolor=c, linewidth='2.0', alpha=alpha))
        if len(plot_line) > 0:
            for l in plot_line:
                ax[j, k].plot(l[0], l[1], 'k--')
        ax[j, k].set_xlim([0, 1])
        ax[j, k].set_ylim([0, 1])
        if k == 3:
            cbar = colorbar.ColorbarBase(ax[j, -1], cmap=cmap, format='%.1f', ticks=[0.0, 0.5, 1.0])
            cbar.ax.set_yticklabels([0.0, 0.5, 1.0])
            ax[j, -1].set_ylabel('Predictor y', size=12)
    plt.show()
    if not filename == '':
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example 6
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    draw_if_interactive()
    return ret 
Example 7
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    draw_if_interactive()
    return ret 
Example 8
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def _colorbar_extension_shape(spacing):
    '''
    Produce 4 colorbars with rectangular extensions for either uniform
    or proportional spacing.

    Helper function for test_colorbar_extension_shape.
    '''
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=4)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        # Create a subplot.
        cax = fig.add_subplot(4, 1, i + 1)
        # Turn off text and ticks.
        for item in cax.get_xticklabels() + cax.get_yticklabels() +\
                cax.get_xticklines() + cax.get_yticklines():
            item.set_visible(False)
        # Generate the colorbar.
        cb = ColorbarBase(cax, cmap=cmap, norm=norm,
                boundaries=boundaries, values=values,
                extend=extension_type, extendrect=True,
                orientation='horizontal', spacing=spacing)
    # Return the figure to the caller.
    return fig 
Example 9
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def _colorbar_extension_length(spacing):
    '''
    Produce 12 colorbars with variable length extensions for either
    uniform or proportional spacing.

    Helper function for test_colorbar_extension_length.
    '''
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=.6)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        for j, extendfrac in enumerate((None, 'auto', 0.1)):
            # Create a subplot.
            cax = fig.add_subplot(12, 1, i*3 + j + 1)
            # Turn off text and ticks.
            for item in cax.get_xticklabels() + cax.get_yticklabels() +\
                    cax.get_xticklines() + cax.get_yticklines():
                item.set_visible(False)
            # Generate the colorbar.
            cb = ColorbarBase(cax, cmap=cmap, norm=norm,
                    boundaries=boundaries, values=values,
                    extend=extension_type, extendfrac=extendfrac,
                    orientation='horizontal', spacing=spacing)
    # Return the figure to the caller.
    return fig 
Example 10
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def test_colorbar_extension_shape():
    '''Test rectangular colorbar extensions.'''
    # Create figures for uniform and proportionally spaced colorbars.
    fig1 = _colorbar_extension_shape('uniform')
    fig2 = _colorbar_extension_shape('proportional') 
Example 11
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def test_colorbar_extension_length():
    '''Test variable length colorbar extensions.'''
    # Create figures for uniform and proportionally spaced colorbars.
    fig1 = _colorbar_extension_length('uniform')
    fig2 = _colorbar_extension_length('proportional') 
Example 12
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def test_colorbar_single_scatter():
    # Issue #2642: if a path collection has only one entry,
    # the norm scaling within the colorbar must ensure a
    # finite range, otherwise a zero denominator will occur in _locate.
    plt.figure()
    x = np.arange(4)
    y = x.copy()
    z = np.ma.masked_greater(np.arange(50, 54), 50)
    cmap = plt.get_cmap('jet', 16)
    cs = plt.scatter(x, y, z, c=z, cmap=cmap)
    plt.colorbar(cs) 
Example 13
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def _test_remove_from_figure(use_gridspec):
    """
    Test `remove_from_figure` with the specified ``use_gridspec`` setting
    """
    fig = plt.figure()
    ax = fig.add_subplot(111)
    sc = ax.scatter([1, 2], [3, 4], cmap="spring")
    sc.set_array(np.array([5, 6]))
    pre_figbox = np.array(ax.figbox)
    cb = fig.colorbar(sc, use_gridspec=use_gridspec)
    fig.subplots_adjust()
    cb.remove()
    fig.subplots_adjust()
    post_figbox = np.array(ax.figbox)
    assert (pre_figbox == post_figbox).all() 
Example 14
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def test_remove_from_figure_with_gridspec():
    """
    Make sure that `remove_from_figure` removes the colorbar and properly
    restores the gridspec
    """
    _test_remove_from_figure(True) 
Example 15
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 5 votes vote down vote up
def test_remove_from_figure_no_gridspec():
    """
    Make sure that `remove_from_figure` removes a colorbar that was created
    without modifying the gridspec
    """
    _test_remove_from_figure(False) 
Example 16
Project: neural-network-animation   Author: miloharper   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    draw_if_interactive()
    return ret 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    return ret 
Example 18
Project: python3_ios   Author: holzschu   File: test_colors.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example 19
Project: python3_ios   Author: holzschu   File: test_colors.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cmap_and_norm_from_levels_and_colors():
    data = np.linspace(-2, 4, 49).reshape(7, 7)
    levels = [-1, 2, 2.5, 3]
    colors = ['red', 'green', 'blue', 'yellow', 'black']
    extend = 'both'
    cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)

    ax = plt.axes()
    m = plt.pcolormesh(data, cmap=cmap, norm=norm)
    plt.colorbar(m)

    # Hide the axes labels (but not the colorbar ones, as they are useful)
    ax.tick_params(labelleft=False, labelbottom=False) 
Example 20
Project: python3_ios   Author: holzschu   File: pyplot.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    return ret 
Example 21
Project: NoisePy   Author: mdenolle   File: noise_module.py    License: MIT License 5 votes vote down vote up
def spect(tr,fmin = 0.1,fmax = None,wlen=10,title=None):
    import matplotlib as plt
    if fmax is None:
        fmax = tr.stats.sampling_rate/2
    fig = plt.figure()
    ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
    ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
    ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

    #make time vector
    t = np.arange(tr.stats.npts) / tr.stats.sampling_rate

    #plot waveform (top subfigure)    
    ax1.plot(t, tr.data, 'k')

    #plot spectrogram (bottom subfigure)
    tr2 = tr.copy()
    fig = tr2.spectrogram(per_lap=0.9,wlen=wlen,show=False, axes=ax2)
    mappable = ax2.images[0]
    plt.colorbar(mappable=mappable, cax=ax3)
    ax2.set_ylim(fmin, fmax)
    ax2.set_xlabel('Time [s]')
    ax2.set_ylabel('Frequency [Hz]')
    if title:
        plt.suptitle(title)
    else:
        plt.suptitle('{}.{}.{} {}'.format(tr.stats.network,tr.stats.station,
                  tr.stats.channel,tr.stats.starttime))
    plt.show() 
Example 22
Project: coffeegrindsize   Author: jgagneastro   File: test_colors.py    License: MIT License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example 23
Project: coffeegrindsize   Author: jgagneastro   File: test_colors.py    License: MIT License 5 votes vote down vote up
def test_cmap_and_norm_from_levels_and_colors():
    data = np.linspace(-2, 4, 49).reshape(7, 7)
    levels = [-1, 2, 2.5, 3]
    colors = ['red', 'green', 'blue', 'yellow', 'black']
    extend = 'both'
    cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)

    ax = plt.axes()
    m = plt.pcolormesh(data, cmap=cmap, norm=norm)
    plt.colorbar(m)

    # Hide the axes labels (but not the colorbar ones, as they are useful)
    ax.tick_params(labelleft=False, labelbottom=False) 
Example 24
Project: coffeegrindsize   Author: jgagneastro   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    return ret 
Example 25
Project: CogAlg   Author: boris-kz   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()
    ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kw)
    return ret 
Example 26
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_colors.py    License: MIT License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example 27
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_colors.py    License: MIT License 5 votes vote down vote up
def test_cmap_and_norm_from_levels_and_colors():
    data = np.linspace(-2, 4, 49).reshape(7, 7)
    levels = [-1, 2, 2.5, 3]
    colors = ['red', 'green', 'blue', 'yellow', 'black']
    extend = 'both'
    cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)

    ax = plt.axes()
    m = plt.pcolormesh(data, cmap=cmap, norm=norm)
    plt.colorbar(m)

    # Hide the axes labels (but not the colorbar ones, as they are useful)
    ax.tick_params(labelleft=False, labelbottom=False) 
Example 28
Project: twitter-stock-recommendation   Author: alvarobartt   File: pyplot.py    License: MIT License 5 votes vote down vote up
def colorbar(mappable=None, cax=None, ax=None, **kw):
    if mappable is None:
        mappable = gci()
        if mappable is None:
            raise RuntimeError('No mappable was found to use for colorbar '
                               'creation. First define a mappable such as '
                               'an image (with imshow) or a contour set ('
                               'with contourf).')
    if ax is None:
        ax = gca()

    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
    return ret 
Example 29
Project: defragTrees   Author: sato9hara   File: RForest.py    License: MIT License 4 votes vote down vote up
def plot(self, X, d1, d2, alpha=0.8, treenum=5, filename=None, box0=None, plot_line=[]):
        
        # boxes
        num = X.shape[0]
        dim = X.shape[1]
        if box0 is None:
            box0 = np.zeros((2, dim))
            for d in range(dim):
                box0[0, d] = np.min(X[:, d])
                box0[1, d] = np.max(X[:, d])
        box0 = box0.astype(np.float64)
        boxes = []
        for n in range(num):
            box = box0.copy()
            for j, tree in enumerate(self.trees_):
                if j >= treenum:
                    break
                i = 0
                while True:
                    if tree.left_[i] == -1:
                        break
                    else:
                        if X[n, tree.index_[i]] <= tree.threshold_[i]:
                            box[1, tree.index_[i]] = min(box[1, tree.index_[i]], tree.threshold_[i])
                            i = tree.left_[i]
                        else:
                            box[0, tree.index_[i]] = max(box[0, tree.index_[i]], tree.threshold_[i])
                            i = tree.right_[i]
            flg = True
            for b in boxes:
                flg *= np.max(np.abs(b[1] - box)) > 1e-8
            if flg:
                pred = self.predict(X[n, :][np.newaxis, :])[0]
                boxes.append((pred, box))
        n = len(boxes)
        
        # plot
        cmap = cm.get_cmap('cool')
        fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
        for b in boxes:
            pred = b[0]
            box = b[1]
            c = cmap(1.0 * pred)
            ax1.add_patch(pl.Rectangle(xy=[box[0, d1], box[0, d2]], width=(box[1, d1] - box[0, d1]), height=(box[1, d2] - box[0, d2]), facecolor=c, linewidth='1.0', alpha=alpha))
        if len(plot_line) > 0:
            ax1.plot(plot_line[0], plot_line[1], 'k--')
        ax1.set_xlabel('x1', size=22)
        ax1.set_ylabel('x2', size=22)
        ax1.set_title('Learned Ensemble', size=28)
        colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
        ax2.set_ylabel('Predictor y', size=22)
        plt.show()
        if not filename is None:
            plt.savefig(filename.replace('.pdf', '_%d.pdf' % (n,)), format="pdf", bbox_inches="tight")
            plt.close() 
Example 30
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    License: MIT License 4 votes vote down vote up
def test_colorbar_positioning():
    data = np.arange(1200).reshape(30, 40)
    levels = [0, 200, 400, 600, 800, 1000, 1200]

    # -------------------
    plt.figure()
    plt.contourf(data, levels=levels)
    plt.colorbar(orientation='horizontal', use_gridspec=False)

    locations = ['left', 'right', 'top', 'bottom']
    plt.figure()
    for i, location in enumerate(locations):
        plt.subplot(2, 2, i + 1)
        plt.contourf(data, levels=levels)
        plt.colorbar(location=location, use_gridspec=False)

    # -------------------
    plt.figure()
    # make some other data (random integers)
    data_2nd = np.array([[2, 3, 2, 3], [1.5, 2, 2, 3], [2, 3, 3, 4]])
    # make the random data expand to the shape of the main data
    data_2nd = np.repeat(np.repeat(data_2nd, 10, axis=1), 10, axis=0)

    color_mappable = plt.contourf(data, levels=levels, extend='both')
    # test extend frac here
    hatch_mappable = plt.contourf(data_2nd, levels=[1, 2, 3], colors='none',
                                  hatches=['/', 'o', '+'], extend='max')
    plt.contour(hatch_mappable, colors='black')

    plt.colorbar(color_mappable, location='left', label='variable 1',
                 use_gridspec=False)
    plt.colorbar(hatch_mappable, location='right', label='variable 2',
                 use_gridspec=False)

    # -------------------
    plt.figure()
    ax1 = plt.subplot(211, anchor='NE', aspect='equal')
    plt.contourf(data, levels=levels)
    ax2 = plt.subplot(223)
    plt.contourf(data, levels=levels)
    ax3 = plt.subplot(224)
    plt.contourf(data, levels=levels)

    plt.colorbar(ax=[ax2, ax3, ax1], location='right', pad=0.0, shrink=0.5,
                 panchor=False, use_gridspec=False)
    plt.colorbar(ax=[ax2, ax3, ax1], location='left', shrink=0.5,
                 panchor=False, use_gridspec=False)
    plt.colorbar(ax=[ax1], location='bottom', panchor=False,
                 anchor=(0.8, 0.5), shrink=0.6, use_gridspec=False)