Exemplo n.º 1
0
def add_interpolated_colorbar(da, colors, direction):
    """
    Add 'rastered' colorbar to DrawingArea
    """
    # Special case that arises due to not so useful
    # aesthetic mapping.
    if len(colors) == 1:
        colors = [colors[0], colors[0]]

    # Number of horizontal egdes(breaks) in the grid
    # No need to create more nbreak than colors, provided
    # no. of colors = no. of breaks = no. of cmap colors
    # the shading does a perfect interpolation
    nbreak = len(colors)

    if direction == 'vertical':
        mesh_width = 1
        mesh_height = nbreak-1
        linewidth = da.height/mesh_height
        # Construct rectangular meshgrid
        # The values(Z) at each vertex are just the
        # normalized (onto [0, 1]) vertical distance
        x = np.array([0, da.width])
        y = np.arange(0, nbreak) * linewidth
        X, Y = np.meshgrid(x, y)
        Z = Y/y.max()
    else:
        mesh_width = nbreak-1
        mesh_height = 1
        linewidth = da.width/mesh_width
        x = np.arange(0, nbreak) * linewidth
        y = np.array([0, da.height])
        X, Y = np.meshgrid(x, y)
        Z = X/x.max()

    # As a 2D coordinates array
    coordinates = np.zeros(
        ((mesh_width+1)*(mesh_height+1), 2),
        dtype=float)
    coordinates[:, 0] = X.ravel()
    coordinates[:, 1] = Y.ravel()

    cmap = ListedColormap(colors)
    coll = mcoll.QuadMesh(mesh_width, mesh_height,
                          coordinates,
                          antialiased=False,
                          shading='gouraud',
                          linewidth=0,
                          cmap=cmap,
                          array=Z.ravel())
    da.add_artist(coll)
Exemplo n.º 2
0
def drawColouredQuadMaps(plt, decoUser, (nelem, npoin, ndp, nplan), (x, y,
                                                                     ikle, z)):

    # ~~> Focus on current subplot / axes instance
    crax = plt.gca()
    # ~~> Plot data
    colourmap = cm.jet
    #if 'cmapPlot' in geometry:
    #   colourmap = LinearSegmentedColormap('User', getColourMap(geometry['cmapPlot']))
    zmin = np.min(z)
    zmax = np.max(z)

    nx = npoin - nelem
    ny = int(npoin / nx)
    mesh = np.column_stack((x, y))
    msh = collections.QuadMesh(nx - 1, ny - 1, mesh, True, shading='gouraud')
    #msh.set_array(np.zeros(self.x_cells*self.y_cells))
    #msh.set_array(np.array(self.FD.GetTimestepData(0)))
    #msh.set_clim(0.0, 1.0)
    #axis.axis([0, self.x_max, 0, self.y_top])
    #plt.colorbar(self.cax)
    ###!!! I have tried cax and msh, and various combos
    #toolbar.show()
    #canvas.draw()
    msh.set_array(z)
    crax.add_collection(msh)

    #cs = plt.tricontour(x,y,ikle, z, linewidths=0.5, colors='k')
    #ex: colors='k' or colors=('r', 'g', 'b', (1,1,0), '#afeeee', '1')
    #plt.tricontourf(x,y,ikle, z, cmap=colourmap)
    # adds numbers along the iso-contours
Exemplo n.º 3
0
def exemplo_8():
    Fs = 250.0
    Ts = 1 / Fs
    start = 2000.0
    end = 3000.0
    depth = np.arange(start, end + Ts, Ts)

    freq = 60.0
    amp = 20
    data2 = amp * np.sin(depth * 2 * np.pi * freq)

    print(depth, len(depth))

    t02 = 2200.0
    t12 = 2400.0
    time2 = np.arange(t02, t12, Ts)
    i, = np.where(depth == t02)
    j, = np.where(depth == t12)

    print(i, j)

    f2 = 100.0  #/128.0
    x2 = np.sin(time2 * 2 * np.pi * f2)

    print(len(x2))

    #  data2[50000:100000] = 1#+= x2

    print('\nWaveletTransform')
    c = Chronometer()
    factor = 1
    Dj = 0.500 / factor
    wa = WaveletTransform(data2, dt=Ts, dj=Dj, time=depth)  #dt=Ts)
    print(c.end())
    """
    # Phase 
    wt = np.copy(wa.wavelet_transform)
    threshold = np.max(np.abs(wt))/10
    wt[np.where(np.abs(wt) < threshold)] = 0
    to_plot = np.unwrap(np.angle(wt))   
    #to_plot = np.angle(wt)
    """
    """
    # Magnitude
    to_plot = np.abs(wa.wavelet_transform)
    """

    #"""
    # Power
    to_plot = wa.wavelet_power
    #"""

    print('\nmeshgrid')
    c = Chronometer()
    x_axis = wa.fourier_frequencies
    y_axis = wa.time

    mesh_x, mesh_y = np.meshgrid(x_axis, y_axis)
    print(c.end())
    '''
    for x in mesh_x:
        print 
        print x, len(x)
 
    print '\n\n\n'
    
    for y in mesh_y:
        print 
        print y, len(y)
    
    '''
    print('\ncontourf')
    c = Chronometer()

    fig, ax = plt.subplots(ncols=1, figsize=(8, 4))

    #####

    import matplotlib.collections as mcoll
    import matplotlib.colors as mcolors
    import matplotlib.transforms as mtransforms

    kwargs = {}
    alpha = None
    norm = None
    cmap = plt.cm.jet
    vmin = None
    vmax = None
    shading = 'flat'
    antialiased = False
    kwargs.setdefault('edgecolors', 'None')

    allmatch = False

    X, Y, C = _pcolorargs('pcolormesh',
                          mesh_x,
                          mesh_y,
                          to_plot.T,
                          allmatch=allmatch)
    Ny, Nx = X.shape

    # convert to one dimensional arrays
    C = C.ravel()
    X = X.ravel()
    Y = Y.ravel()

    #print X
    #print Y
    #raise Exception()

    # unit conversion allows e.g. datetime objects as axis values
    ax._process_unit_info(xdata=X, ydata=Y, kwargs=kwargs)
    X = ax.convert_xunits(X)
    Y = ax.convert_yunits(Y)
    '''
    print '\n'
    for x in X:
        print x
    print '\n'
    '''

    print('\n')
    print(X[0], X[-1], len(X))
    print('\n')

    coords = np.zeros(((Nx * Ny), 2), dtype=float)
    coords[:, 0] = X
    coords[:, 1] = Y

    collection = mcoll.QuadMesh(Nx - 1,
                                Ny - 1,
                                coords,
                                antialiased=antialiased,
                                shading=shading,
                                **kwargs)
    collection.set_alpha(alpha)
    collection.set_array(C)
    if norm is not None and not isinstance(norm, mcolors.Normalize):
        msg = "'norm' must be an instance of 'mcolors.Normalize'"
        raise ValueError(msg)
    collection.set_cmap(cmap)
    collection.set_norm(norm)
    collection.set_clim(vmin, vmax)
    collection.autoscale_None()

    ax.grid(False)
    """
    # Transform from native to data coordinates?
    t = collection._transform
    print '\nt:', t
    if (not isinstance(t, mtransforms.Transform) and hasattr(t, '_as_mpl_transform')):
        print 'E1'
        t = t._as_mpl_transform(ax.axes)

    if t and any(t.contains_branch_seperately(ax.transData)):
        trans_to_data = t - ax.transData
        pts = np.vstack([X, Y]).T.astype(np.float)
        transformed_pts = trans_to_data.transform(pts)
        X = transformed_pts[..., 0]
        Y = transformed_pts[..., 1]
    """

    ax.add_collection(collection, autolim=False)

    minx = np.amin(X)
    maxx = np.amax(X)
    miny = np.amin(Y)
    maxy = np.amax(Y)
    collection.sticky_edges.x[:] = [minx, maxx]
    collection.sticky_edges.y[:] = [miny, maxy]
    corners = (minx, miny), (maxx, maxy)

    print(corners)

    ax.update_datalim(corners)
    ax.autoscale_view()
    ret = collection

    #####

    #ax2.pcolormesh(x, y, np.flipud(data))
    #ret = ax.pcolormesh(mesh_x, mesh_y, to_plot.T, cmap=plt.cm.jet)

    #ret = plt.contourf(mesh_x, mesh_y, to_plot.T, 20, cmap=plt.cm.jet)#, 100, cmap=plt.cm.jet)
    print(c.end())

    print(ret)

    #plt.xscale('log')

    #plt.xlim(x_axis[-1], x_axis[0])
    plt.ylim(y_axis[-1], y_axis[0])

    #plt.grid(True)

    plt.show()
Exemplo n.º 4
0
    def pcolormesh(self, *args, **kwargs):
        import warnings
        import numpy as np
        import numpy.ma as ma
        import matplotlib as mpl
        import matplotlib.cbook as cbook
        import matplotlib.colors as mcolors
        import matplotlib.cm as cm
        from matplotlib import docstring
        import matplotlib.transforms as transforms
        import matplotlib.artist as artist
        from matplotlib.artist import allow_rasterization
        import matplotlib.backend_bases as backend_bases
        import matplotlib.path as mpath
        import matplotlib.mlab as mlab
        import matplotlib.collections as mcoll
        
        if not self._hold: self.cla()

        alpha = kwargs.pop('alpha', None)
        norm = kwargs.pop('norm', None)
        cmap = kwargs.pop('cmap', None)
        vmin = kwargs.pop('vmin', None)
        vmax = kwargs.pop('vmax', None)
        shading = kwargs.pop('shading', 'flat').lower()
        antialiased = kwargs.pop('antialiased', False)
        kwargs.setdefault('edgecolors', 'None')

        X, Y, C = self._pcolorargs('pcolormesh', *args)
        Ny, Nx = X.shape

        # convert to one dimensional arrays
        if shading != 'gouraud':
            C = ma.ravel(C[0:Ny-1, 0:Nx-1]) # data point in each cell is value at
                                            # lower left corner
        else:
            C = C.ravel()
        X = X.ravel()
        Y = Y.ravel()

        coords = np.zeros(((Nx * Ny), 2), dtype=float)
        coords[:, 0] = X
        coords[:, 1] = Y

        collection = mcoll.QuadMesh(
            Nx - 1, Ny - 1, coords,
            antialiased=antialiased, shading=shading, **kwargs)
        collection.set_alpha(alpha)
        collection.set_array(C)
        if norm is not None: assert(isinstance(norm, mcolors.Normalize))
        collection.set_cmap(cmap)
        collection.set_norm(norm)
        collection.set_clim(vmin, vmax)
        collection.autoscale_None()

        self.grid(False)

        # Transform from native to data coordinates?
        t = collection._transform
        if (not isinstance(t, mtransforms.Transform)
            and hasattr(t, '_as_mpl_transform')):
            t = t._as_mpl_transform(self.axes)

        if t and any(t.contains_branch_seperately(self.transData)):
            trans_to_data = t - self.transData
            pts = np.vstack([X, Y]).T.astype(np.float)
            transformed_pts = trans_to_data.transform(pts)
            X = transformed_pts[..., 0]
            Y = transformed_pts[..., 1]

            # XXX Not a mpl 1.2 thing...
            no_inf = (X != np.inf) & (Y != np.inf)
            X = X[no_inf]
            Y = Y[no_inf]

        minx = np.amin(X)
        maxx = np.amax(X)
        miny = np.amin(Y)
        maxy = np.amax(Y)
        
        corners = (minx, miny), (maxx, maxy)
        self.update_datalim( corners)
        self.autoscale_view()
        self.add_collection(collection)
        return collection