Python matplotlib.pyplot.clabel() Examples

The following are code examples for showing how to use matplotlib.pyplot.clabel(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: RLControl   Author: sungsulim   File: environments.py    Apache License 2.0 6 votes vote down vote up
def plot_reward_func(self):
        x = np.linspace(self.state_min[0], self.state_max[0], 50)
        y = np.linspace(self.state_min[1], self.state_max[1], 50)
        X, Y = np.meshgrid(x, y)
        Z = self.reward_func([X, Y])
        contours = plt.contour(X, Y, Z)

        plt.clabel(contours, inline=True, fontsize=5)

        plt.imshow(Z, extent=[self.state_min[0], self.state_max[0], self.state_min[1], self.state_max[1]], origin='lower',
                   cmap='inferno', alpha=0.5)
        plt.colorbar()
        plt.show()


    # Close the environment and clear memory 
Example 2
Project: Speech-Recognition   Author: ncble   File: test_cma_lu.py    Apache License 2.0 6 votes vote down vote up
def draw_surface_level(fun, centre = np.zeros(2), taille = 1.0, message = None):

		plt.figure(figsize=(5, 3))
		axes = plt.gca()
		if message:
			plt.title(message)
		x_min, y_min = (centre - taille)#[0,0], (centre - taille)[0,1]  #X[:, 0].min()
		x_max, y_max = (centre + taille)#[0,0], (centre + taille)[0,1]     #X[:, 0].max()
		
		axes.set_xlim([x_min,x_max])
		axes.set_ylim([y_min,y_max])
		XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]

		Z = fun(np.c_[XX.ravel(), YY.ravel()])

		# Put the result into a color plot
		Z = Z.reshape(XX.shape)
		plt.pcolormesh(XX, YY, Z, cmap = plt.cm.jet)
		# CS = plt.contour(XX, YY, Z, cmap = plt.cm.jet)
		# plt.clabel(CS, fmt='%2.1f', colors='b', fontsize=14)
		plt.show() 
Example 3
Project: ble5-nrf52-mac   Author: tomasero   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 4
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 6 votes vote down vote up
def test_contour_badlevel_fmt():
    # test funny edge case from
    # https://github.com/matplotlib/matplotlib/issues/9742
    # User supplied fmt for each level as a dictionary, but
    # MPL changed the level to the minimum data value because
    # no contours possible.
    # This would error out pre
    # https://github.com/matplotlib/matplotlib/pull/9743
    x = np.arange(9)
    z = np.zeros((9, 9))

    fig, ax = plt.subplots()
    fmt = {1.: '%1.2f'}
    with pytest.warns(UserWarning) as record:
        cs = ax.contour(x, x, z, levels=[1.])
        ax.clabel(cs, fmt=fmt)
    assert len(record) == 1 
Example 5
Project: MachineLearning_Python   Author: lawlite19   File: AnomalyDetection.py    MIT License 6 votes vote down vote up
def visualizeFit(X,mu,sigma2):
    x = np.arange(0, 36, 0.5) # 0-36,步长0.5
    y = np.arange(0, 36, 0.5)
    X1,X2 = np.meshgrid(x,y)  # 要画等高线,所以meshgird
    Z = multivariateGaussian(np.hstack((X1.reshape(-1,1),X2.reshape(-1,1))), mu, sigma2)  # 计算对应的高斯分布函数
    Z = Z.reshape(X1.shape)  # 调整形状
    plt.plot(X[:,0],X[:,1],'bx')
    
    if np.sum(np.isinf(Z).astype(float)) == 0:   # 如果计算的为无穷,就不用画了
        #plt.contourf(X1,X2,Z,10.**np.arange(-20, 0, 3),linewidth=.5)
        CS = plt.contour(X1,X2,Z,10.**np.arange(-20, 0, 3),color='black',linewidth=.5)   # 画等高线,Z的值在10.**np.arange(-20, 0, 3)
        #plt.clabel(CS)
            
    plt.show()

# 选择最优的epsilon,即:使F1Score最大 
Example 6
Project: neural-network-animation   Author: miloharper   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 7
Project: neural-network-animation   Author: miloharper   File: test_contour.py    MIT License 6 votes vote down vote up
def test_labels():
    # Adapted from pylab_examples example code: contour_demo.py
    # see issues #2475, #2843, and #2818 for explanation
    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    # difference of Gaussians
    Z = 10.0 * (Z2 - Z1)

    fig, ax = plt.subplots(1, 1)
    CS = ax.contour(X, Y, Z)
    disp_units = [(216, 177), (359, 290), (521, 406)]
    data_units = [(-2, .5), (0, -1.5), (2.8, 1)]

    CS.clabel()

    for x, y in data_units:
        CS.add_label_near(x, y, inline=True, transform=None)

    for x, y in disp_units:
        CS.add_label_near(x, y, inline=True, transform=False) 
Example 8
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 6 votes vote down vote up
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options):
    """Makes a pseudocolor plot.
    
    xs:
    ys:
    zs:
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    X, Y = np.meshgrid(xs, ys)
    Z = zs

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)

    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10) 
Example 9
Project: python3_ios   Author: holzschu   File: test_patheffects.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 10
Project: python3_ios   Author: holzschu   File: test_contour.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_contour_badlevel_fmt():
    # test funny edge case from
    # https://github.com/matplotlib/matplotlib/issues/9742
    # User supplied fmt for each level as a dictionary, but
    # MPL changed the level to the minimum data value because
    # no contours possible.
    # This would error out pre
    # https://github.com/matplotlib/matplotlib/pull/9743
    x = np.arange(9)
    z = np.zeros((9, 9))

    fig, ax = plt.subplots()
    fmt = {1.: '%1.2f'}
    with pytest.warns(UserWarning) as record:
        cs = ax.contour(x, x, z, levels=[1.])
        ax.clabel(cs, fmt=fmt)
    assert len(record) == 1 
Example 11
Project: monsoon-onset   Author: jenfly   File: pub-figs-grl.py    MIT License 6 votes vote down vote up
def pts_clim(index_pts, nm, clev_bar=10, clev_std=np.arange(0, 21, 1),
             axlims=(5, 32, 60, 100), cmap='spectral', res='l',
             label_locs=None, inline_spacing=2):
    """Plot climatological mean and standard deviation of grid point indices."""
    varbar = index_pts[nm].mean(dim='year')
    varstd = index_pts[nm].std(dim='year')
    lat1, lat2, lon1, lon2 = axlims
    m = atm.init_latlon(lat1, lat2, lon1, lon2, resolution=res)
    m = atm.contourf_latlon(varstd, m=m, clev=clev_std, axlims=axlims, cmap=cmap,
                            symmetric=False, colorbar=False, extend='max')
    m.colorbar(ticks=np.arange(0, 21, 2))
    _, cs = atm.contour_latlon(varbar, clev=clev_bar, axlims=axlims, colors='k',
                               linewidths=2)
    cs_opts = {'fmt' : '%.0f', 'fontsize' : 9,
               'inline_spacing' : inline_spacing}
    if label_locs is not None:
        cs_opts['manual'] = label_locs
    plt.clabel(cs, **cs_opts)
    plot_kerala()
    fix_axes(axlims)

# Plot regression 
Example 12
Project: linear_neuron   Author: uglyboxer   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 13
Project: cubic_reg   Author: cjones6   File: example.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_points(self, intermediate_points):
        xlist = np.linspace(-3.0, 3.0, 50)
        ylist = np.linspace(-3.0, 3.0, 50)
        X, Y = np.meshgrid(xlist, ylist)
        Z = np.zeros_like(X)
        for i in range(0, len(X)):
            for j in range(0, len(X)):
                Z[i, j] = self.f((X[i, j], Y[i, j]))
        points = np.asarray(intermediate_points)
        plt.clf()
        cp = plt.contour(X, Y, Z)
        plt.clabel(cp, inline=True, fontsize=10)
        plt.plot(points[:, 0], points[:, 1])
        plt.title('Contour plot of function and path of cubic regularization algorithm')
        plt.xlabel('x')
        plt.ylabel('y')
        plt.xlim(-3, 3)
        plt.ylim(-3, 3)
        plt.show() 
Example 14
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 15
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_contour.py    MIT License 6 votes vote down vote up
def test_contour_badlevel_fmt():
    # test funny edge case from
    # https://github.com/matplotlib/matplotlib/issues/9742
    # User supplied fmt for each level as a dictionary, but
    # MPL changed the level to the minimum data value because
    # no contours possible.
    # This would error out pre
    # https://github.com/matplotlib/matplotlib/pull/9743
    x = np.arange(9)
    z = np.zeros((9, 9))

    fig, ax = plt.subplots()
    fmt = {1.: '%1.2f'}
    with pytest.warns(UserWarning) as record:
        cs = ax.contour(x, x, z, levels=[1.])
        ax.clabel(cs, fmt=fmt)
    assert len(record) == 1 
Example 16
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 17
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_contour.py    MIT License 6 votes vote down vote up
def test_contour_badlevel_fmt():
    # test funny edge case from
    # https://github.com/matplotlib/matplotlib/issues/9742
    # User supplied fmt for each level as a dictionary, but
    # MPL changed the level to the minimum data value because
    # no contours possible.
    # This would error out pre
    # https://github.com/matplotlib/matplotlib/pull/9743
    x = np.arange(9)
    z = np.zeros((9, 9))

    fig, ax = plt.subplots()
    fmt = {1.: '%1.2f'}
    with pytest.warns(UserWarning) as record:
        cs = ax.contour(x, x, z, levels=[1.])
        ax.clabel(cs, fmt=fmt)
    assert len(record) == 1 
Example 18
Project: ImageFusion   Author: pfchai   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 19
Project: PorousMediaLab   Author: biogeochemistry   File: plotter.py    MIT License 6 votes vote down vote up
def saturation_index_countour(lab, elem1, elem2, Ks, labels=False):
    plt.figure()
    plt.title('Saturation index %s%s' % (elem1, elem2))
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    plt.xlabel('Time')
    z = np.log10((lab.species[elem1]['concentration'][:, ::n] + 1e-8) * (
        lab.species[elem2]['concentration'][:, ::n] + 1e-8) / lab.constants[Ks])
    lim = np.max(abs(z))
    lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[::n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette(
        "RdBu_r", 101)), origin='lower', levels=lim, extend='both')
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    # cbar = plt.colorbar(CS)
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Saturation index %s%s' % (elem1, elem2))
    return ax 
Example 20
Project: PorousMediaLab   Author: biogeochemistry   File: plotter.py    MIT License 6 votes vote down vote up
def contour_plot_of_rates(lab, r, labels=False, last_year=False):
    plt.figure()
    plt.title('{}'.format(r))
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    if last_year:
        k = n - int(1 / lab.dt)
    else:
        k = 1
    z = lab.estimated_rates[r][:, k - 1:-1:n]
    # lim = np.max(np.abs(z))
    # lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[k::n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(
        sns.color_palette("Blues", 51)))
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Rate %s [M/V/T]' % r)
    return ax 
Example 21
Project: PorousMediaLab   Author: biogeochemistry   File: plotter.py    MIT License 6 votes vote down vote up
def contour_plot_of_delta(lab, element, labels=False, last_year=False):
    plt.figure()
    plt.title('Rate of %s consumption/production' % element)
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    if last_year:
        k = n - int(1 / lab.dt)
    else:
        k = 1
    z = lab.species[element]['rates'][:, k - 1:-1:n]
    lim = np.max(np.abs(z))
    lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[k:-1:n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette(
        "RdBu_r", 101)), origin='lower', levels=lim, extend='both')
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Rate of %s change $[\Delta/T]$' % element)
    return ax 
Example 22
Project: Blackjack-Tracker   Author: martinabeleda   File: test_patheffects.py    MIT License 6 votes vote down vote up
def test_collection():
    x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
    data = np.sin(x) + np.cos(y)
    cs = plt.contour(data)
    pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
                                       linewidth=12),
          path_effects.Stroke(linewidth=5)]

    for collection in cs.collections:
        collection.set_path_effects(pe)

    for text in plt.clabel(cs, colors='white'):
        text.set_path_effects([path_effects.withStroke(foreground='k',
                                                       linewidth=3)])
        text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
                       'edgecolor': 'blue'}) 
Example 23
Project: Blackjack-Tracker   Author: martinabeleda   File: test_contour.py    MIT License 6 votes vote down vote up
def test_labels():
    # Adapted from pylab_examples example code: contour_demo.py
    # see issues #2475, #2843, and #2818 for explanation
    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    # difference of Gaussians
    Z = 10.0 * (Z2 - Z1)

    fig, ax = plt.subplots(1, 1)
    CS = ax.contour(X, Y, Z)
    disp_units = [(216, 177), (359, 290), (521, 406)]
    data_units = [(-2, .5), (0, -1.5), (2.8, 1)]

    CS.clabel()

    for x, y in data_units:
        CS.add_label_near(x, y, inline=True, transform=None)

    for x, y in disp_units:
        CS.add_label_near(x, y, inline=True, transform=False) 
Example 24
Project: PyMICAPS   Author: flashlxy   File: Map.py    GNU General Public License v2.0 5 votes vote down vote up
def DrawContourAndMark(contour, x, y, z, level, clipborder, patch, m):

        # 是否绘制等值线 ------ 等值线和标注是一体的

        if contour.contour['visible']:

            matplotlib.rcParams['contour.negative_linestyle'] = 'dashed'
            if contour.contour['colorline']:
                CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth'])
            else:
                CS1 = m.contour(x,
                                y,
                                z,
                                levels=level,
                                linewidths=contour.contour['linewidth'],
                                colors=contour.contour['linecolor'])

            # 是否绘制等值线标注
            CS2 = None
            if contour.contourlabel['visible']:
                CS2 = plt.clabel(CS1,
                                 inline=1,
                                 fmt=contour.contourlabel['fmt'],
                                 inline_spacing=contour.contourlabel['inlinespacing'],
                                 fontsize=contour.contourlabel['fontsize'],
                                 colors=contour.contourlabel['fontcolor'])

            # 用区域边界裁切等值线图
            if clipborder.path is not None and clipborder.using:
                for collection in CS1.collections:
                    # collection.set_clip_on(True)
                    collection.set_clip_path(patch)

                if CS2 is not None:
                    for text in CS2:
                        if not clipborder.path.contains_point(text.get_position()):
                            text.remove() 
Example 25
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_2d_parscans(image_arrays=[], axis=[], fig_handle=None, labels=[], cmap='coolwarm', boundaries=[],
                     interpolation='nearest', display=True, **kwargs):
    """
    Plots a list of arrays as images in the corresponding axis with the corresponding colorbar

    :return:
    """
    assert len(image_arrays) == len(axis), "Number of provided arrays must match number of axes"

    origin = 'upper'
    for idx, ax in enumerate(axis):
        if not isinstance(ax, mpl.axes.Axes):
            raise ValueError('ax must be matplotlib.axes.Axes instance.')
        else:
            plt1 = ax.imshow(image_arrays[idx], aspect='auto', origin=origin, cmap=cmap, interpolation=interpolation)
            if boundaries:
                cont = ax.contour(image_arrays[idx], boundaries[idx], origin='lower', colors='k', linewidths=2)
                pl.clabel(cont, fmt='%2.1f', colors='k', fontsize=12)
            if labels:
                ax.set_title(labels[idx])
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", "10%", pad="4%")
            if fig_handle is not None:
                # cbar = fig_handle.colorbar(plt1, cax=cax, format='%.2f')
                cbar = fig_handle.colorbar(plt1, cax=cax)
                cbar.ax.tick_params(labelsize=15)
            ax.set(**kwargs)
            pl.draw()
    if display:
        pl.show(block=False) 
Example 26
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_3d_parscans(image_arrays=[], axis=[], dimensions=[10, 10, 10], fig_handle=None, labels=[], cmap='jet',
                     boundaries=[],
                     **kwargs):
    """
    Plot results when 3 different parameter axes are used.. (needs further testing)
    :return:
    """
    assert(has_mayavi), "mayavi required"
    assert len(image_arrays) == len(axis), "Number of provided arrays mus match number of axes"
    x = np.linspace(0, dimensions[0], 1)
    y = np.linspace(0, dimensions[1], 1)
    z = np.linspace(0, dimensions[2], 1)

    X1, Y1, Z1 = np.meshgrid(x, y, z)

    origin = 'upper'
    for idx, ax in enumerate(axis):
        if not isinstance(ax, mpl.axes.Axes):
            raise ValueError('ax must be matplotlib.axes.Axes instance.')
        else:
            plt1 = ax.imshow(image_arrays[idx], aspect='auto', interpolation='nearest', origin=origin, cmap=cmap)

            if boundaries:
                cont = ax.contour(image_arrays[idx], boundaries[idx], origin='lower', colors='k', linewidths=2)
                pl.clabel(cont, fmt='%2.1f', colors='k', fontsize=12)
            if labels:
                ax.set_title(labels[idx])
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", "10%", pad="4%")
            if fig_handle is not None:
                cbar = fig_handle.colorbar(plt1, cax=cax)

            ax.set(**kwargs)
            pl.draw()
    pl.show(block=False) 
Example 27
Project: ble5-nrf52-mac   Author: tomasero   File: test_patheffects.py    MIT License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")]) 
Example 28
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contour_manual_labels():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2), dpi=200)
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts) 
Example 29
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contour_labels_size_color():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2))
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g')) 
Example 30
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_circular_contour_warning():
    # Check that almost circular contours don't throw a warning
    with pytest.warns(None) as record:
        x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
        r = np.sqrt(x ** 2 + y ** 2)

        plt.figure()
        cs = plt.contour(x, y, r)
        plt.clabel(cs)
    assert len(record) == 0 
Example 31
Project: improved_driving_functions_for_rectangular_loudspeaker_arrays   Author: spatialaudio   File: 25d_esa_field.py    MIT License 5 votes vote down vote up
def plot_sound_field_level(p, xs, twin):

    plt.style.use(('paper.mplstyle', 'paper_box.mplstyle'))
    fig = plt.figure()
    ax1 = fig.add_axes([0.0, 0.0, 0.7, 1])
    im = sfs.plot.level(p, grid, xnorm=None, colorbar=False, cmap=plt.cm.viridis, vmax=3, vmin=-3, ax=ax1)
    CS = plt.contour(sfs.util.db(p), 1, levels=[0], origin='lower', linewidths=2, extent=(0, 4, -4, 0), colors='w', alpha=.5)
    plt.clabel(CS, [0], inline=1, fmt='%1.1f dB', fontsize=8, rightside_up=1)
    zc = CS.collections[0]
    plt.setp(zc, linewidth=0.5)

    plot_objects(plt.gca(), xs)
    plt.annotate('4m', (-2.5, 2), (-2.75, -2.4), arrowprops={'arrowstyle': '<->'}) 

    plt.axis([-1.1, 4.2, -4.2, 1.1])
    plt.axis('off')

    ax2 = fig.add_axes([0.55, -0.05, 0.25, .95])
    plt.axis('off')
    cbar = plt.colorbar(im, ax=ax2, shrink=.6)
    cbar.set_label('relative level (dB)', rotation=270, labelpad=10)
    cbar.set_ticks(np.arange(-3, 4))

    myfig = plt.gcf()
    plt.show()
    if save_figures:
        if wfs:
            myfig.savefig('../paper/figs/edge_wfs_25d_point_%dHz_%d_L.pdf' % (f, src_angles[n]), dpi=300)
        else:
            myfig.savefig('../paper/figs/edge_esa_25d_point_%dHz_%d_L.pdf' % (f, src_angles[n]), dpi=300)


# get secondary source positions 
Example 32
Project: improved_driving_functions_for_rectangular_loudspeaker_arrays   Author: spatialaudio   File: 2d_esa_field.py    MIT License 5 votes vote down vote up
def plot_sound_field_level(p, xs, twin):
    plt.style.use(('paper.mplstyle', 'paper_box.mplstyle'))

    fig = plt.figure()
    ax1 = fig.add_axes([0.0, 0.0, 0.7, 1])
    im = sfs.plot.level(p, grid, xnorm=None, colorbar=False, cmap=plt.cm.viridis, vmax=3, vmin=-3, ax=ax1)
    CS = plt.contour(sfs.util.db(p), 1, levels=[0], origin='lower', linewidths=2, extent=(0,4,-4,0), colors='w', alpha=.5)
    plt.clabel(CS, [0], inline=1, fmt='%1.1f dB', fontsize=8, rightside_up=1)
    zc = CS.collections[0]
    plt.setp(zc, linewidth=0.5)

    plot_objects(plt.gca(), xs)
    plt.annotate('4m', (-2.5, 2), (-2.75, -2.4), arrowprops={'arrowstyle': '<->'}) 

    plt.axis([-1.1, 4.2, -4.2, 1.1])
    plt.axis('off')

    ax2 = fig.add_axes([0.55, -0.05, 0.25, .95])
    plt.axis('off')
    cbar = plt.colorbar(im, ax=ax2, shrink=.6, aspect=15)
    cbar.set_label('relative level (dB)', rotation=270, labelpad=15)
    cbar.set_ticks(np.arange(-3, 4))

    myfig = plt.gcf()
    plt.show()
    if save_figures:
        if wfs:
            myfig.savefig('../paper/figs/edge_wfs_2d_line_%dHz_%d_L.pdf' % (f, src_angles[n]),  transparent=True)
        else:
            myfig.savefig('../paper/figs/edge_esa_2d_line_%dHz_%d_L.pdf' % (f, src_angles[n]),  transparent=True)


# get secondary source positions 
Example 33
Project: neural-network-animation   Author: miloharper   File: test_patheffects.py    MIT License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")]) 
Example 34
Project: neural-network-animation   Author: miloharper   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contour_manual_labels():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2))
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts) 
Example 35
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 5 votes vote down vote up
def Contour(obj, pcolor=False, contour=True, imshow=False, **options):
    """Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use plt.imshow
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    try:
        d = obj.GetDict()
    except AttributeError:
        d = obj

    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    xs, ys = zip(*d.keys())
    xs = sorted(set(xs))
    ys = sorted(set(ys))

    X, Y = np.meshgrid(xs, ys)
    func = lambda x, y: d.get((x, y), 0)
    func = np.vectorize(func)
    Z = func(X, Y)

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)
    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10)
    if imshow:
        extent = xs[0], xs[-1], ys[0], ys[-1]
        plt.imshow(Z, extent=extent, **options) 
Example 36
Project: GradVis   Author: cc-hpc-itwm   File: trajectory_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def contour_loss(X,Y,Z,path_x=[],path_y=[],labels=[], filename="out", is_log=False):
    """
    Creates a 2D-plot of the loss and with the trajectory taken.

    Args:
        X, Y, Z: x,y,z-components of loss landscape.
        path_(x,y,z): x,y,z-components of path values.
        filename: name of the plot that is saved.
        labels: [x,y]-label used in the plot.
        is_log (boolean): plot the logarithmic loss landscape and trajectory.
    """
    if is_log:
        scale = lambda x: np.log(x)
    else:
        scale = lambda x: x

    fig = plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k', frameon=False)
    CS = plt.contour(X, Y, scale(Z),100,zorder=0)

    if len(path_x)!=0 and len(path_y)!=0:
        NPOINTS=len(path_x)
        cmap = matplotlib.cm.get_cmap('hot')
        normalize = matplotlib.colors.Normalize(vmin=0, vmax=NPOINTS)
        colors = [cmap(normalize(value)) for value in range(NPOINTS)]
        As0 = plt.plot(path_x,path_y, color="k",markersize=0, alpha=1,zorder=8)
        As = plt.scatter(path_x,path_y,color=colors[::-1],edgecolor='k',alpha=1,zorder=10)
        As1 = plt.plot(path_x[0],path_y[0], markerfacecolor='k', markeredgecolor='k', marker='v', markersize=10, alpha=1,zorder=10)
        As1 = plt.plot(path_x[-1],path_y[-1], markerfacecolor='r', markeredgecolor='r', marker='X', markersize=10, alpha=1,zorder=10)

    plt.clabel(CS, inline=1, fontsize=10)
    plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=False)
    plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False)
    if len(labels)!= 0:
        plt.xlabel(str(labels[0]))
        plt.ylabel(str(labels[1]))

    fig_savename='%s.svg'%(filename)
    print('Saving figure %s'%fig_savename)
    fig.savefig(fig_savename, dpi=300, format='svg')
    plt.close(fig) 
Example 37
Project: python3_ios   Author: holzschu   File: test_patheffects.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")]) 
Example 38
Project: python3_ios   Author: holzschu   File: test_contour.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_contour_manual_labels():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2), dpi=200)
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts) 
Example 39
Project: python3_ios   Author: holzschu   File: test_contour.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_contour_labels_size_color():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2))
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g')) 
Example 40
Project: python3_ios   Author: holzschu   File: test_contour.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_circular_contour_warning():
    # Check that almost circular contours don't throw a warning
    with pytest.warns(None) as record:
        x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
        r = np.sqrt(x ** 2 + y ** 2)

        plt.figure()
        cs = plt.contour(x, y, r)
        plt.clabel(cs)
    assert len(record) == 0 
Example 41
Project: Milano   Author: NVIDIA   File: bbob_func_eval.py    Apache License 2.0 5 votes vote down vote up
def visualize_function(self, func, show_3d=True, show_3d_inv=True,
                         show_contour=True, num_levels=15, rng_x=(-5, 5),
                         rng_y=(-5, 5)):
    import matplotlib.pyplot as plt
    if self._dim == 1:
      xs = np.linspace(rng_x[0], rng_x[1], 100)
      plt.plot(xs, np.apply_along_axis(func, 0, xs[np.newaxis, :]))
    elif self._dim == 2:
      freq = 50
      x = np.linspace(rng_x[0], rng_x[1], freq)
      y = np.linspace(rng_y[0], rng_y[1], freq)
      Xs, Ys = np.meshgrid(x, y)
      xs = np.reshape(Xs, -1)
      ys = np.reshape(Ys, -1)
      zs = np.apply_along_axis(func, 0, np.vstack((xs, ys)))

      if show_3d:
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca(projection='3d')
        ax.plot_trisurf(xs, ys, zs, linewidth=0.2, antialiased=True)
        plt.show()
      if show_3d_inv:
        fig = plt.figure(figsize=(10, 10))
        ax = fig.gca(projection='3d')
        ax.invert_zaxis()
        ax.plot_trisurf(xs, ys, zs, linewidth=0.2, antialiased=True)
        plt.show()
      if show_contour:
        fig = plt.figure(figsize=(10, 10))
        cs = plt.contour(Xs, Ys, zs.reshape(freq, freq), num_levels)
        plt.clabel(cs, inline=1, fontsize=10)
        plt.show()
    else:
      raise ValueError("Only dim=1 or dim=2 are supported") 
Example 42
Project: monsoon-onset   Author: jenfly   File: pub-figs-jclim.py    MIT License 5 votes vote down vote up
def precip_frac(pcp_frac, m=None):
    _, cs = atm.contour_latlon(pcp_frac, m=m, clev=np.arange(0, 1, 0.1),
                               linewidths=1.5, colors='k',
                               axlims=(0, 35, 58, 102))
    label_locs = [(80, 5), (75, 6), (72, 8), (72, 10), (70, 15), (70, 18),
                  (72, 25), (84, 5), (60, 5), (65, 3), (95, 18)]
    cs_opts = {'fmt' : '%.1f', 'fontsize' : 9, 'manual' : label_locs,
               'inline_spacing' : 2}
    plt.clabel(cs, **cs_opts) 
Example 43
Project: linear_neuron   Author: uglyboxer   File: test_patheffects.py    MIT License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")]) 
Example 44
Project: mpb-plotting   Author: FilipDominec   File: plot_dispersion_and_modes.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_IFC(Kx, Ky, freqs):#{{{

    ## Plot the iso-frequency contours (IFC)
    #                           np.linspace(0., 1., 100)
    plt.title('IFC for band %d' % selectband)
    plt.legend(prop={'size':10}, loc='upper right')
    plt.contourf(Kx, Ky, freqs*fcoef/funit, 50, cmap=cm.jet); plt.colorbar()
    plt.clabel(plt.contour(Kx, Ky, freqs*fcoef/funit, colors='k', levels=np.arange(0., funit*10, funit/10)))


    plt.annotate("$\Gamma$", xy = (.001, .001), xytext = (10, 10),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round, pad=.15', fc='white', alpha=0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    plt.annotate("X", xy = (.499,.001), xytext = (-10, 10),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round, pad=.15', fc='white', alpha=0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    plt.annotate("M", xy = (.499,.499), xytext = (-10, -10),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round, pad=.15', fc='white', alpha=0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

    plt.xlabel(u"$K_x a /(2\\pi)$"); plt.ylabel(u"$K_y a /(2\\pi)$"); 
    plt.xlim((0,.5)); plt.ylim((0,.5))
    plt.grid(True)
#}}} 
Example 45
Project: Think-Bayes   Author: foamliu   File: thinkplot.py    Apache License 2.0 5 votes vote down vote up
def Contour(obj, pcolor=False, contour=True, imshow=False, **options):
    """Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use pyplot.imshow
    options: keyword args passed to pyplot.pcolor and/or pyplot.contour
    """
    try:
        d = obj.GetDict()
    except AttributeError:
        d = obj

    Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    xs, ys = zip(*d.keys())
    xs = sorted(set(xs))
    ys = sorted(set(ys))

    X, Y = np.meshgrid(xs, ys)
    func = lambda x, y: d.get((x, y), 0)
    func = np.vectorize(func)
    Z = func(X, Y)

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = pyplot.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        pyplot.pcolormesh(X, Y, Z, **options)
    if contour:
        cs = pyplot.contour(X, Y, Z, **options)
        pyplot.clabel(cs, inline=1, fontsize=10)
    if imshow:
        extent = xs[0], xs[-1], ys[0], ys[-1]
        pyplot.imshow(Z, extent=extent, **options) 
Example 46
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_patheffects.py    MIT License 5 votes vote down vote up
def test_patheffect2():

    ax2 = plt.subplot(111)
    arr = np.arange(25).reshape((5, 5))
    ax2.imshow(arr)
    cntr = ax2.contour(arr, colors="k")

    plt.setp(cntr.collections,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")])

    clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
    plt.setp(clbls,
             path_effects=[path_effects.withStroke(linewidth=3,
                                                   foreground="w")]) 
Example 47
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contour_manual_labels():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2), dpi=200)
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts) 
Example 48
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contour_labels_size_color():

    x, y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
    z = np.max(np.dstack([abs(x), abs(y)]), 2)

    plt.figure(figsize=(6, 2))
    cs = plt.contour(x, y, z)
    pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
    plt.clabel(cs, manual=pts, fontsize='small', colors=('r', 'g')) 
Example 49
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_contour.py    MIT License 5 votes vote down vote up
def test_circular_contour_warning():
    # Check that almost circular contours don't throw a warning
    with pytest.warns(None) as record:
        x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
        r = np.hypot(x, y)

        plt.figure()
        cs = plt.contour(x, y, r)
        plt.clabel(cs)
    assert len(record) == 0 
Example 50
Project: snippets   Author: jeremiedecock   File: label_on_contours_and_heat_map.py    MIT License 5 votes vote down vote up
def main():
    """The main function."""

    # Build data ################

    matplotlib.rcParams['xtick.direction'] = 'out'
    matplotlib.rcParams['ytick.direction'] = 'out'

    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)

    #Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    #Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    #Z = 10.0 * (Z2 - Z1)  # difference of Gaussians
    
    Z = X * np.exp(-X**2 - Y**2)


    # Plot data #################

    ## Plot contour
    #CS = plt.contour(X, Y, Z)
    #plt.clabel(CS, inline=1, fontsize=10)

    ## Plot heat map
    #im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    # Plot contour
    CS = ax.contour(X, Y, Z)
    ax.clabel(CS, inline=1, fontsize=10)

    # Plot heat map
    im = ax.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2))

    plt.show()