Python matplotlib.pyplot.tricontourf() Examples

The following are code examples for showing how to use matplotlib.pyplot.tricontourf(). 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: tectosaur   Author: tbenthompson   File: test_regularized.py    MIT License 6 votes vote down vote up
def plot_fnc(m, surf1_idxs, surf2_idxs, x, outs):
    def plot_at_pts(idxs, f):
        pts_f = np.full(m[0].shape[0], np.nan)
        pts_f[m[1][idxs]] = f

        pts_f_not_nan = pts_f[np.logical_not(np.isnan(pts_f))]
        min_f = np.min(pts_f_not_nan)
        max_f = np.max(pts_f_not_nan)

        plt.figure()
        plt.tricontourf(
            m[0][:,0], m[0][:,2], m[1], pts_f,
            levels = np.linspace(min_f, max_f, 21),
            extend = 'both'
        )
        plt.colorbar()


    for d in range(3):
        plot_at_pts(surf2_idxs, x[:,d].reshape((-1,3)))
        for o in outs:
            plot_at_pts(surf1_idxs, o.reshape(-1,3,3)[:,:,d])
        plt.show() 
Example 2
Project: nanopores   Author: mitschabaude   File: matplotfem2d.py    MIT License 6 votes vote down vote up
def fem2contour(u):
    mesh = u.function_space().mesh()
    v2d = dolfin.vertex_to_dof_map(u.function_space())
    
    # extract x and y coordinates of nodes
    x = mesh.coordinates()[:,0]
    y = mesh.coordinates()[:,1]
    triangles = mesh.cells()
    
    # Create triangulation.
    triang = mtri.Triangulation(x, y, triangles)
    
    # create array of node values from function
    z = u.vector()[v2d]

    # Plot the triangulation.
    plt.figure()
    plt.tricontourf(triang, z)
    #plt.triplot(triang, 'k-')
    #plt.title('Triangular grid') 
Example 3
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_triangulation.py    MIT License 6 votes vote down vote up
def test_tricontour_non_finite_z():
    # github issue 10167.
    x = [0, 1, 0, 1]
    y = [0, 0, 1, 1]
    triang = mtri.Triangulation(x, y)
    plt.figure()

    with pytest.raises(ValueError, match='z array must not contain non-finite '
                                         'values within the triangulation'):
        plt.tricontourf(triang, [0, 1, 2, np.inf])

    with pytest.raises(ValueError, match='z array must not contain non-finite '
                                         'values within the triangulation'):
        plt.tricontourf(triang, [0, 1, 2, -np.inf])

    with pytest.raises(ValueError, match='z array must not contain non-finite '
                                         'values within the triangulation'):
        plt.tricontourf(triang, [0, 1, 2, np.nan])

    with pytest.raises(ValueError, match='z must not contain masked points '
                                         'within the triangulation'):
        plt.tricontourf(triang, np.ma.array([0, 1, 2, 3], mask=[1, 0, 0, 0])) 
Example 4
Project: tectosaur   Author: tbenthompson   File: okada.py    MIT License 5 votes vote down vote up
def gauss_fault_slip(pts, fault_tris, gauss_z):
    dof_pts = pts[fault_tris]
    x = dof_pts[:,:,0]
    z = dof_pts[:,:,2]
    mean_z = np.mean(z)
    slip = np.zeros((fault_tris.shape[0], 3, 3))
    # slip[:,:,0] = (1 - np.abs(x)) * (1 - np.abs((z - mean_z) * 2.0))
    # slip[:,:,1] = (1 - np.abs(x)) * (1 - np.abs((z - mean_z) * 2.0))
    # slip[:,:,2] = (1 - np.abs(x)) * (1 - np.abs((z - mean_z) * 2.0))
    slip[:,:,0] = gauss_slip_fnc(x, z, gauss_z)

    # slip_pts = np.zeros(pts.shape[0])
    # # slip_pts[fault_tris] = np.log10(np.abs(slip[:,:,0]))
    # slip_pts[fault_tris] = slip[:,:,0]
    # plt.tricontourf(pts[:,0], pts[:,2], fault_tris, slip_pts)
    # plt.triplot(pts[:,0], pts[:,2], fault_tris)
    # dof_pts = pts[fault_tris]
    # plt.xlim([np.min(dof_pts[:,:,0]), np.max(dof_pts[:,:,0])])
    # plt.ylim([np.min(dof_pts[:,:,2]), np.max(dof_pts[:,:,2])])
    # plt.colorbar()
    # plt.show()

    # idxs = np.where(pts[:,2] == 0.0)[0]
    # idxs = np.intersect1d(idxs, fault_tris.flatten())
    # x = pts[idxs,0]
    # s = slip_pts[idxs]
    # plt.plot(x, s, '.')
    # plt.show()
    # for I in idxs:
    #     tri_idxs, basis_idxs = np.where(fault_tris == I)
    #     slip[tri_idxs, basis_idxs,0] = 0.0

    return slip 
Example 5
Project: tectosaur   Author: tbenthompson   File: interior.py    MIT License 5 votes vote down vote up
def plot_fnc(triang, f):
    levels = np.linspace(np.min(f) - 1e-12, np.max(f) + 1e-12, 21)
    cntf = plt.tricontourf(triang, f, levels = levels, cmap = 'RdBu')
    plt.tricontour(triang, f, levels = levels, linestyles = 'solid', colors = 'k', linewidths = 0.5)
    plt.colorbar(cntf) 
Example 6
Project: tectosaur   Author: tbenthompson   File: interior_ick.py    MIT License 5 votes vote down vote up
def plot_fnc(triang, f):
    levels = np.linspace(np.min(f) - 1e-12, np.max(f) + 1e-12, 21)
    cntf = plt.tricontourf(triang, f, levels = levels, cmap = 'RdBu')
    plt.tricontour(triang, f, levels = levels, linestyles = 'solid', colors = 'k', linewidths = 0.5)
    plt.colorbar(cntf) 
Example 7
Project: tectosaur   Author: tbenthompson   File: inverse_tools.py    MIT License 5 votes vote down vote up
def plot_surf_disp(m, side, field, name, vmin = None, vmax = None, filename = None, view_R = 1.0, proj = None, latlon_step = 0.5):
    fC, R = get_fault_centered_view(m)

    if vmin is None:
        vmin = np.min(field)
    if vmax is None:
        vmax = np.max(field)
    cmap = 'PuOr_r'
    levels = np.linspace(vmin, vmax, 17)

    plt.figure(figsize = (10,10))
    fault_start_idx = m.get_start('fault')
    for i in range(2):
        which_tris = np.where(np.logical_or(side[:fault_start_idx] == 0, side[:fault_start_idx] == i + 1))[0]
        reduced_m = mesh_fncs.remove_unused_pts((m.pts, m.tris[which_tris]))
        soln_vals = np.empty(reduced_m[0].shape[0])
        soln_vals[reduced_m[1]] = field[which_tris]

        triang = tri.Triangulation(reduced_m[0][:,0], reduced_m[0][:,1], triangles = reduced_m[1])
        tri_refi, interp_vals = triang, soln_vals
        cntf = plt.tricontourf(tri_refi, interp_vals, cmap = cmap, levels = levels, extend = 'both')
        plt.tricontour(
            tri_refi, interp_vals, levels = levels,
            colors = '#333333', linestyles = 'solid', linewidths = 0.75
        )

    plot_fault_trace(m)


    cbar = plt.colorbar(cntf)
    cbar.set_label('$\\text{displacement (m)}$')

    map_axis(fC, R, view_R, proj, latlon_step)

    plt.title(name)
    if filename is not None:
        plt.savefig(filename)
    plt.show() 
Example 8
Project: tectosaur   Author: tbenthompson   File: map_view_parallel.py    MIT License 5 votes vote down vote up
def f(idx, filepath):
    """ Main rendering function """
    plt.figure(figsize=(6, 6))
    contour_levels = np.linspace(VMIN, VMAX, 11)
    fig = plt.figure(figsize=(7, 7))
    ax = plt.subplot(1, 1, 1, aspect=1)
    mesh = plt.tricontourf(
        pts[:, 0],
        pts[:, 1],
        tris,
        slip_rate_log[idx, :],
        contour_levels,
        cmap="plasma",
        vmin=VMIN,
        vmax=VMAX,
        extend="both",
    )

    plot_boundary(tris, outline=False)
    plot_whiskers(idx)
    plt.gca().set_aspect("equal")
    plt.xlabel("x (km)")
    plt.ylabel("y (km)")
    plt.xticks([0, 400])
    plt.yticks([0, 400, 800, 1200])
    plt.xlim([np.min(pts[:, 0]) - BUFFER_KM, np.max(pts[:, 0]) + BUFFER_KM])
    plt.ylim([np.min(pts[:, 1]) - BUFFER_KM, np.max(pts[:, 1]) + BUFFER_KM])
    plt.title(format_title(t[idx]), fontsize=10)

    m = plt.cm.ScalarMappable(cmap="plasma")
    m.set_array(slip_rate_log)
    m.set_clim(VMIN, VMAX)
    cbar_axes = fig.add_axes([0.35, 0.1, 0.015, 0.3])
    cbar = plt.colorbar(m, boundaries=contour_levels, cax=cbar_axes)
    cbar.set_ticks(np.array([-11, -9, -7, -5, -3, -1]))
    cbar.set_label("log v")
    plt.tight_layout()
    plt.savefig(filepath, dpi=300) 
Example 9
Project: ble5-nrf52-mac   Author: tomasero   File: test_triangulation.py    MIT License 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 10
Project: python3_ios   Author: holzschu   File: test_triangulation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 11
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_triangulation.py    MIT License 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 12
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_triangulation.py    MIT License 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 13
Project: Blackjack-Tracker   Author: martinabeleda   File: test_triangulation.py    MIT License 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 14
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_triangulation.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tricontourf_decreasing_levels():
    # github issue 5477.
    x = [0.0, 1.0, 1.0]
    y = [0.0, 0.0, 1.0]
    z = [0.2, 0.4, 0.6]
    plt.figure()
    with pytest.raises(ValueError):
        plt.tricontourf(x, y, z, [1.0, 0.0]) 
Example 15
Project: master   Author: kewitz   File: NScheme.py    MIT License 5 votes vote down vote up
def plotResult(self, result):
        t = self.triangulate()
        plt.tricontourf(t, result, 15, cmap=plt.cm.rainbow)
        plt.colorbar()
        plt.show() 
Example 16
Project: master   Author: kewitz   File: EScheme.py    MIT License 5 votes vote down vote up
def plotResult(self, result):
        t = self.triangulate()
        plt.tricontourf(t, result, 15, cmap=plt.cm.rainbow)
        plt.colorbar()
        plt.show() 
Example 17
Project: SolidsPy   Author: AppliedMechanics-EAFIT   File: postprocesor.py    MIT License 5 votes vote down vote up
def tri_plot(tri, field, title="", levels=12, savefigs=False,
             plt_type="contourf", filename="solution_plot.pdf"):
    """Plot contours over triangulation

    Parameters
    ----------
    tri : ndarray (float)
        Array with number and nodes coordinates:
        `number coordX coordY BCX BCY`
    field : ndarray (float)
        Array with data to be plotted for each node.
    title : string (optional)
        Title of the plot.
    levels : int (optional)
        Number of levels to be used in ``contourf``.
    savefigs : bool (optional)
        Allow to save the figure.
    plt_type : string (optional)
        Plot the field as one of the options: ``pcolor`` or
        ``contourf``
    filename : string (optional)
        Filename to save the figures.
    """
    if plt_type == "pcolor":
        disp_plot = plt.tripcolor
    elif plt_type == "contourf":
        disp_plot = plt.tricontourf
    disp_plot(tri, field, levels, shading="gouraud")
    plt.title(title)
    plt.colorbar(orientation='vertical')
    plt.axis("image")
    if savefigs:
        plt.savefig(filename) 
Example 18
Project: BERNAISE   Author: gautelinga   File: plot.py    MIT License 5 votes vote down vote up
def plot_contour(nodes, elems, vals,
                 title=None, clabel=None,
                 save=None, show=True, latex=False):
    """ Contour plot; values given at nodes. """
    fig = Figure(title=title, clabel=clabel, save=save, show=show, latex=latex)
    fig.colorbar_ax = plt.tricontourf(nodes[:, 0], nodes[:, 1], elems, vals)
    return fig 
Example 19
Project: BERNAISE   Author: gautelinga   File: plot.py    MIT License 5 votes vote down vote up
def plot_quiver(nodes, elems, vals, title=None, clabel=None,
                save=None, show=True, latex=False):
    """ Plots quivers with contour in the background.
    Values given at nodes. """
    fig = Figure(title=title, subplots=True, clabel=clabel,
                 save=save, show=show, latex=latex)

    vals_norm = np.sqrt(vals[:, 0]**2 + vals[:, 1]**2) + 1e-10
    # vals_norm_max = np.max(vals_norm)
    fig.colorbar_ax = fig.ax.tricontourf(nodes[:, 0], nodes[:, 1], elems,
                                         vals_norm)
    fig.ax.quiver(nodes[:, 0], nodes[:, 1],
                  vals[:, 0]/vals_norm, vals[:, 1]/vals_norm) 
Example 20
Project: tectosaur   Author: tbenthompson   File: plotting.py    MIT License 4 votes vote down vote up
def plot_fields(model, field, which = 'fault', levels = None, cmap = 'seismic',
        symmetric_scale = False, ds = None, figsize = None, dims = [0,2],
        xlim = None, ylim = None, figscale = (6,5), filepath = None):

    field_reshape = field.reshape((model.m.n_tris(which) * 3, -1))
    n_fields = field_reshape.shape[1]

    if figsize is None:
        figsize = (figscale[0] * n_fields,figscale[1])
    plt.figure(figsize = figsize)

    which_tris = model.m.get_tris(which)
    plot_f = dofs_to_pts(model.m.pts, which_tris, model.basis_dim, field_reshape)
    which_pts_idxs = np.unique(which_tris)
    which_pts = model.m.pts[which_pts_idxs]
    for d in (range(n_fields) if ds is None else ds):
        plt.subplot(1, n_fields, d + 1)

        f_levels = levels
        if f_levels is None:
            f_levels = get_levels(plot_f[which_pts_idxs,d], symmetric_scale)

        # plt.triplot(
        #     model.m.pts[:,dims[0]], model.m.pts[:,dims[1]], which_tris
        # )
        cntf = plt.tricontourf(
            model.m.pts[:,dims[0]], model.m.pts[:,dims[1]], which_tris, plot_f[:,d],
            cmap = cmap, levels = f_levels, extend = 'both'
        )
        if xlim is None:
            plt.xlim([np.min(which_pts[:,dims[0]]), np.max(which_pts[:,dims[0]])])
        else:
            plt.xlim(xlim)
        if ylim is None:
            plt.ylim([np.min(which_pts[:,dims[1]]), np.max(which_pts[:,dims[1]])])
        else:
            plt.ylim(ylim)
        plt.colorbar(cntf)
    plt.tight_layout()
    if filepath is not None:
        plt.savefig(filepath, bbox_inches = 'tight')
    plt.show() 
Example 21
Project: BERNAISE   Author: gautelinga   File: plot.py    MIT License 4 votes vote down vote up
def plot_streamlines(nodes, elems, vals, title=None, clabel=None,
                     save=None, show=True, num_intp=200, density=0.8, latex=False):
    """ Plots streamlines with contour in the background.
    Values given at nodes. """
    fig = Figure(title=title, subplots=True, clabel=clabel,
                 save=save, show=show, latex=latex)

    vals_norm = np.sqrt(vals[:, 0]**2 + vals[:, 1]**2) + 1e-10
    # vals_norm_max = np.max(vals_norm)
    fig.colorbar_ax = fig.ax.tricontourf(nodes[:, 0], nodes[:, 1], elems,
                                         vals_norm)

    Lx = nodes[:, 0].max()-nodes[:, 0].min()
    Ly = nodes[:, 1].max()-nodes[:, 1].min()
    dx = max(Lx, Ly)/num_intp
    Nx = int(Lx/dx)
    Ny = int(Ly/dx)

    x_i, y_i = np.meshgrid(
        np.linspace(dx+nodes[:, 0].min(),
                    nodes[:, 0].max()-dx, Nx),
        np.linspace(dx+nodes[:, 1].min(),
                    nodes[:, 1].max()-dx, Ny))
    triang = mtri.Triangulation(nodes[:, 0], nodes[:, 1], elems)
    ux_interp = mtri.LinearTriInterpolator(triang, vals[:, 0])
    uy_interp = mtri.LinearTriInterpolator(triang, vals[:, 1])
    ux_i = ux_interp(x_i, y_i)
    uy_i = uy_interp(x_i, y_i)

    ux_i = np.array(ux_i.filled(0.))
    uy_i = np.array(uy_i.filled(0.))

    u_norm = np.sqrt(ux_i**2 + uy_i**2)

    lw = np.zeros_like(ux_i)
    lw[:] += 5*u_norm/(u_norm.max() + 1e-10)

    mask = np.zeros(ux_i.shape, dtype=bool)
    ux_i_2 = np.ma.array(ux_i, mask=mask)

    fig.ax.streamplot(x_i, y_i,
                      ux_i_2, uy_i,
                      color="k",
                      density=density,
                      linewidth=lw)