Exemplo n.º 1
0
def draw_decision_boundary(X, y, model, title):
    resolution = 0.01
    markers = ('o', 's', '^')
    colors = ('lightgreen', 'red', 'blue')
    cmap = mpl.colors.ListedColormap(colors)

    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))

    mpd = model.predict(np.array([xx1.ravel(),
                                  xx2.ravel()]).T).reshape(xx1.shape)

    plt.contour(xx1, xx2, mpd, cmap=mpl.colors.ListedColormap(['k']))
    plt.contourf(xx1, xx2, mpd, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0],
                    y=X[y == cl, 1],
                    alpha=0.8,
                    c=[cmap(idx)],
                    marker=markers[idx],
                    s=80,
                    label=cl)

    plt.xlabel(iris.feature_names[2])
    plt.ylabel(iris.feature_names[3])
    plt.legend(loc='upper left')
    plt.title(title)

    return mpd
Exemplo n.º 2
0
    def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'):
        outdir = self.set_dir(outdir)
        p = 64
        if F is None: F=self.calc_F(u,v)

        plt.close('all')
        plt.figure()
        #fig, axes = plt.subplots(nrows=1)
        if contour:
            plt.hold(True)
            plt.contourf(x,y,F)
        if plot=='quiver':
            plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1)
        
        if plot=='pcolor':
            plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1)
            plt.colorbar()

        if plot=='stream':
            speed = F[::16]
            plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k')

        plt.xlabel('$x$ (a.u.)')
        plt.ylabel('$y$ (a.u.)')
        
        plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight')
        plt.close()
Exemplo n.º 3
0
	def drown_field(self,data,mask,drown):
		''' drown_field is a wrapper around the fortran code fill_msg_grid.
		depending on the output geometry, applies land extrapolation on 1 or N levels'''
		if self.geometry == 'surface':
			for kz in _np.arange(self.nz):
				tmpin = data[kz,:,:].transpose()
				if self.debug and kz == 0:
					tmpin_plt = _np.ma.masked_values(tmpin,self.xmsg)
					_plt.figure() ; _plt.contourf(tmpin_plt.transpose(),40) ; _plt.colorbar() ; 
					_plt.title('normalized before drown')
				if drown == 'ncl':
					tmpout = _fill.mod_poisson.poisxy1(tmpin,self.xmsg, self.guess, self.gtype, \
					self.nscan, self.epsx, self.relc)
				elif drown == 'sosie':
					tmpout = _mod_drown_sosie.mod_drown.drown(self.kew,tmpin,mask[kz,:,:].T,\
					nb_inc=200,nb_smooth=40)
				data[kz,:,:] = tmpout.transpose()
				if self.debug and kz == 0:
					_plt.figure() ; _plt.contourf(tmpout.transpose(),40) ; _plt.colorbar() ; 
					_plt.title('normalized after drown') 
					_plt.show()
		elif self.geometry == 'line':
			tmpin = data[:,:].transpose()
			if drown == 'ncl':
				tmpout = _fill.mod_poisson.poisxy1(tmpin,self.xmsg, self.guess, self.gtype, \
				self.nscan, self.epsx, self.relc)
			elif drown == 'sosie':
				tmpout = _mod_drown_sosie.mod_drown.drown(self.kew,tmpin,mask[:,:].T,\
				nb_inc=200,nb_smooth=40)
			data[:,:] = tmpout.transpose()
		return data
Exemplo n.º 4
0
 def plot(x,y,field,filename,c=200):
     plt.figure()
     # define grid.
     xi = np.linspace(min(x),max(x),100)
     yi = np.linspace(min(y),max(y),100)
     # grid the data.
     si_lin = griddata((x, y), field, (xi[None,:], yi[:,None]), method='linear')
     si_cub = griddata((x, y), field, (xi[None,:], yi[:,None]), method='linear')
     print np.min(field)
     print np.max(field)
     plt.subplot(211)
     # contour the gridded data, plotting dots at the randomly spaced data points.
     CS = plt.contour(xi,yi,si_lin,c,linewidths=0.5,colors='k')
     CS = plt.contourf(xi,yi,si_lin,c,cmap=plt.cm.jet)
     plt.colorbar() # draw colorbar
     # plot data points.
     #    plt.scatter(x,y,marker='o',c='b',s=5)
     plt.xlim(min(x),max(x))
     plt.ylim(min(y),max(y))
     plt.title('Lineaarinen interpolointi')
     #plt.tight_layout()
     plt.subplot(212)
     # contour the gridded data, plotting dots at the randomly spaced data points.
     CS = plt.contour(xi,yi,si_cub,c,linewidths=0.5,colors='k')
     CS = plt.contourf(xi,yi,si_cub,c,cmap=plt.cm.jet)
     plt.colorbar() # draw colorbar
     # plot data points.
     #    plt.scatter(x,y,marker='o',c='b',s=5)
     plt.xlim(min(x),max(x))
     plt.ylim(min(y),max(y))
     plt.title('Kuubinen interpolointi')
     plt.savefig(filename)
Exemplo n.º 5
0
	def perform_interpolation(self,dataextrap,regridme,field_src,field_target,use_locstream):
		data = self.allocate()
		if self.geometry == 'surface':
			for kz in _np.arange(self.nz):
				field_src.data[:] = dataextrap[kz,:,:].transpose()
				field_target = regridme(field_src, field_target)
				if use_locstream:
					if self.nx == 1:
						data[kz,:,0] = field_target.data.copy()
					elif self.ny == 1:
						data[kz,0,:] = field_target.data.copy()
				else:
					data[kz,:,:] = field_target.data.transpose()[self.jmin:self.jmax+1, \
					                                             self.imin:self.imax+1]
					if self.debug and kz == 0:
						data_target_plt = _np.ma.masked_values(data[kz,:,:],self.xmsg)
						#data_target_plt = _np.ma.masked_values(field_target.data,self.xmsg)
						_plt.figure() ; _plt.contourf(data_target_plt[:,:],40) ; _plt.colorbar() ; 
						_plt.title('regridded') ; _plt.show()
		elif self.geometry == 'line':
			field_src.data[:] = dataextrap[:,:].transpose()
			field_target = regridme(field_src, field_target)
			if use_locstream:
				data[:,:] = _np.reshape(field_target.data.transpose(),(self.ny,self.nx))
			else:
				data[:,:] = field_target.data.transpose()[self.jmin:self.jmax+1,self.imin:self.imax+1]
		return data
Exemplo n.º 6
0
def main_k_nearest_neighbour(k):
    X, y = make_blobs(n_samples=100,
                      n_features=2,
                      centers=2,
                      cluster_std=1.0,
                      center_box=(-10.0, 10.0))

    h = .4
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    z = np.c_[xx.ravel(), yy.ravel()]

    z_f = []
    for i_z in z:
        z_f.append(k_nearest_neighbour(X, y, i_z, k, False))

    zz = np.array(z_f).reshape(xx.shape)

    plt.figure()
    plt.contourf(xx, yy, zz, cmap=plt.cm.Paired)
    plt.axis('tight')
    plt.scatter(X[:, 0], X[:, 1], c=y)

    plt.show()
    def drown_field(self, data, mask, drown):
        ''' drown_field is a wrapper around the fortran code fill_msg_grid.
		depending on the output geometry, applies land extrapolation on 1 or N levels'''
        if self.geometry == 'surface':
            for kz in _np.arange(self.nz):
                tmpin = data[kz, :, :].transpose()
                if self.debug and kz == 0:
                    tmpin_plt = _np.ma.masked_values(tmpin, self.xmsg)
                    _plt.figure()
                    _plt.contourf(tmpin_plt.transpose(), 40)
                    _plt.colorbar()
                    _plt.title('normalized before drown')
                if drown == 'ncl':
                    tmpout = _fill.mod_poisson.poisxy1(tmpin,self.xmsg, self.guess, self.gtype, \
                    self.nscan, self.epsx, self.relc)
                elif drown == 'sosie':
                    tmpout = _mod_drown_sosie.mod_drown.drown(self.kew,tmpin,mask[kz,:,:].T,\
                    nb_inc=200,nb_smooth=40)
                data[kz, :, :] = tmpout.transpose()
                if self.debug and kz == 0:
                    _plt.figure()
                    _plt.contourf(tmpout.transpose(), 40)
                    _plt.colorbar()
                    _plt.title('normalized after drown')
                    _plt.show()
        elif self.geometry == 'line':
            tmpin = data[:, :].transpose()
            if drown == 'ncl':
                tmpout = _fill.mod_poisson.poisxy1(tmpin,self.xmsg, self.guess, self.gtype, \
                self.nscan, self.epsx, self.relc)
            elif drown == 'sosie':
                tmpout = _mod_drown_sosie.mod_drown.drown(self.kew,tmpin,mask[:,:].T,\
                nb_inc=200,nb_smooth=40)
            data[:, :] = tmpout.transpose()
        return data
 def perform_extrapolation(self, datasrc, maskfile, maskvar, missing_value,
                           drown):
     # 2.1 read mask or compute it
     if maskvar is not None:
         mask = _ncdf.read_field(maskfile, maskvar)
         # to do, needs imin/imax_src,...
     else:
         mask = self.compute_mask_from_missing_value(
             datasrc, missing_value=missing_value)
     # 2.2 mask the source data
     if _np.ma.is_masked(datasrc):
         datasrc = datasrc.data
     datasrc[_np.where(mask == 0)] = self.xmsg
     datamin = datasrc[_np.where(mask == 1)].min()
     datamax = datasrc[_np.where(mask == 1)].max()
     if self.debug:
         datasrc_plt = _np.ma.masked_values(datasrc, self.xmsg)
         _plt.figure()
         _plt.contourf(datasrc_plt[0, :, :], 40)
         _plt.title('original')
         _plt.colorbar()
     # 2.3 perform land extrapolation on reduced variable
     datanorm = self.normalize(datasrc, datamin, datamax, mask)
     if self.debug:
         print(datanorm.min(), datanorm.max(), datamin, datamax)
     datanormextrap = self.drown_field(datanorm, mask, drown)
     dataextrap = self.unnormalize(datanormextrap, datamin, datamax)
     return dataextrap
def make_2d_surface_contours(x,
                             y,
                             z,
                             title='',
                             x_axis_name='',
                             y_axis_name='',
                             z_axis_name='',
                             extra_contour_line=None):
    fig = plt.figure()
    ax = plt.axes()
    X, Y, Z = grid(x, y, z, resX=187, resY=187)

    if extra_contour_line != None:
        contours2 = plt.contour(X,
                                Y,
                                Z,
                                levels=[extra_contour_line],
                                colors='blue',
                                linestyles=':')
        # plt.plot([0], [0], ls=':',c='blue', label=entry['label'])
    ax.scatter(x, y, c='red', s=2, zorder=5)
    contours = plt.contour(X, Y, Z, colors='black', vmin=0.5, vmax=max(z))
    plt.contourf(X, Y, Z, 100)

    ax.set_xlim([min(x), max(x)])
    ax.set_ylim([min(y), max(y)])

    plt.title(title)
    plt.xlabel(x_axis_name)
    plt.ylabel(y_axis_name)
    cbar = plt.colorbar()
    cbar.ax.set_ylabel(z_axis_name)
    plt.tight_layout()
    plt.show()
    plt.savefig('plot.png')
Exemplo n.º 10
0
def simple_plot(resource, variable=None, output='plot.png'):
    """
    Generates a nice and simple plot.
    """
    print("Plotting {} ...".format(resource))

    # Create dataset from resource ... a local NetCDF file or a remote OpenDAP URL
    ds = Dataset(resource)

    # Get the values of the given variable
    values = ds.variables[variable]

    # Prepare plot with a given size
    fig = plt.figure(figsize=(20, 10))

    # add projection
    ax = plt.axes(projection=ccrs.PlateCarree())

    # Render a contour plot for the first timestep
    plt.contourf(values[0, :, :])

    # add background image with coastlines
    ax.stock_img()
    ax.coastlines()

    # add a colorbar
    plt.colorbar()

    # Save the plot to filesystem
    fig.savefig(output)
    plt.close()
    print("Plot written to {}".format(output))
    return output
    def plot_electric_field(self,sp=10,scales = 500000,cont_scale=90,savefigs = False):

        fig = plt.figure(figsize=(7.0, 7.0))
        xplot = self.x*1e6
        yplot = self.y*1e6
        X,Y = np.meshgrid(xplot,yplot)
        try:
            plt.contourf(X,Y,self.mode_field,cont_scale)
        except AttributeError:
             raise NotImplementedError("interpolate before plotting")

        plt.quiver(X[::sp,::sp], Y[::sp,::sp], np.real(self.E[::sp,::sp,0]), np.real(self.E[::sp,::sp,1]),scale = scales,headlength=7)
        plt.xlabel(r'$x(\mu m)$')
        plt.ylabel(r'$y(\mu m)$')
        #plt.title(r'mode$=$'+str(self.mode)+', '+'  $n_{eff}=$'+str(self.neff.real)+str(self.neff.imag)+'j')
        if savefigs == True:    
            plt.savefig('mode'+str(self.mode)+'.eps',bbox_inches ='tight')
        
            D = {}
            D['X'] = X
            D['Y'] = Y
            D['Z'] = self.mode_field
            D['u'] = np.real(self.E[::sp,::sp,0])
            D['v'] = np.real(self.E[::sp,::sp,1])
            D['scale'] = scales
            D['cont_scale'] = 90
            D['sp'] = sp
            savemat('mode'+str(self.mode)+'.mat',D)
        return None
Exemplo n.º 12
0
def example_plot(xy, labels, a, b, title, filename=None):
    # Shape
    c_shape = ['bs', 'r^']

    # 1. Point
    for k, (point, label) in enumerate(zip(xy, labels), 1):
        x, y = point
        plt.plot(x, y, c_shape[label[0]], mec='k')
        plt.text(x, y, '$P_{}$'.format(k), size=15, \
                 verticalalignment='top', horizontalalignment='left')

    # 2. Decision line
    tmp = np.linspace(0, 1, 500)
    decision_line = a * tmp + b
    plt.plot(tmp, decision_line, 'k-', linewidth=3)

    # 3. Contour
    X, Y = np.meshgrid(tmp, tmp)
    Z = np.zeros_like(X)
    Z[Y > a * X + b] = 1

    plt.contourf(X, Y, Z, cmap='coolwarm')
    # plt.axis('equal')
    plt.grid(linestyle='--', alpha=0.5)
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.title(title)
    if filename:
        plt.savefig(filename, dpi=300)
    plt.show()
Exemplo n.º 13
0
    def plot_decision_regions(X, y, classifier, resolution=0.02):
        maker = ('s', 'x', 'o', 'v')
        colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
        cmap = ListedColormap(colors[:len(np.unique(y))])
        x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
        x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
        # print(x1_min,x1_max)
        # print(x2_min,x2_max)
        xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                               np.arange(x2_min, x2_max, resolution))
        # print(np.arange(x1_min,x1_max,resolution).shape)
        # print(np.arange(x1_min,x1_max,resolution))
        # print(xx1.shape)
        # print(xx1)

        Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
        print(xx1.ravel())
        print(xx2.ravel())
        print(Z)
        Z = Z.reshape(xx1.shape)
        plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
        plt.xlim(xx1.min(), xx1.max())
        plt.ylim(xx2.min(), xx2.max())

        for idx, cl in enumerate(np.unique(y)):
            plt.scatter(x=X[y == cl, 0],
                        y=X[y == cl, 1],
                        alpha=0.8,
                        c=cmap(idx),
                        marker=maker[idx],
                        label=cl)
def main():
    # get Dimensions of the 2D grid.
    OptDB = PETSc.Options()

    n = OptDB.getInt('n', 33)
    nx = OptDB.getInt('nx', n)
    ny = OptDB.getInt('ny', n)

    # run solution
    pde, time = solvePoisson(nx, ny)

    # Plot solution
    show_solution = OptDB.getBool('plot_solution', 0)
    if show_solution:
        pylab.figure()
        pylab.contourf(pde.da.getVecArray(pde.x)[:])
        pylab.colorbar()

    # plot convergence behavior
    pylab.figure()
    rh = pde.ksp.getConvergenceHistory()
    pylab.semilogy(range(len(rh)), rh, 'b-o')
    pylab.xlabel('Iterations')
    pylab.ylabel('||r||_2')
    pylab.title('Convergence Behavior {0}, time={1:8.6f} s'.format(
        pde.solver_name, time))
    pylab.grid()
    pylab.show()
Exemplo n.º 15
0
def plot_decision_surface(axes, clusters, X, Y=None):
    import matplotlib.pylab as pylab
    import numpy as np

    def kmeans_predict(clusters, X):
        from ..core import distance
        dist_m = distance.minkowski_dist(clusters, X)
        print 'dist_m:', dist_m.shape
        pred = np.argmin(dist_m, axis=0)
        print 'pred:', pred.shape
        return pred

    # step size in the mesh
    h = (np.max(X, axis=0) - np.min(X, axis=0)) / 100.0
    # create a mesh to plot in
    x_min = np.min(X, axis=0) - 1
    x_max = np.max(X, axis=0) + 1
    xx, yy = np.meshgrid(np.arange(x_min[0], x_max[0], h[0]),
                         np.arange(x_min[1], x_max[1], h[1]))
    Z = kmeans_predict(clusters, np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pylab.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z, cmap=pylab.cm.Paired)
    pylab.xlim(np.min(xx), np.max(xx))
    pylab.ylim(np.min(yy), np.max(yy))
    #pylab.axis('off')

    # Plot also the training points
    if Y is not None:
        pylab.scatter(X[:,0], X[:,1], c=Y)
    else:
        pylab.scatter(X[:,0], X[:,1])
    pylab.scatter(clusters[:,0], clusters[:,1], s=200, marker='x', color='white')
 def perform_interpolation(self, dataextrap, regridme, field_src,
                           field_target, use_locstream):
     data = self.allocate()
     if self.geometry == 'surface':
         for kz in _np.arange(self.nz):
             field_src.data[:] = dataextrap[kz, :, :].transpose()
             field_target = regridme(field_src, field_target)
             if use_locstream:
                 if self.nx == 1:
                     data[kz, :, 0] = field_target.data.copy()
                 elif self.ny == 1:
                     data[kz, 0, :] = field_target.data.copy()
             else:
                 data[kz,:,:] = field_target.data.transpose()[self.jmin:self.jmax+1, \
                                                              self.imin:self.imax+1]
                 if self.debug and kz == 0:
                     data_target_plt = _np.ma.masked_values(
                         data[kz, :, :], self.xmsg)
                     #data_target_plt = _np.ma.masked_values(field_target.data,self.xmsg)
                     _plt.figure()
                     _plt.contourf(data_target_plt[:, :], 40)
                     _plt.colorbar()
                     _plt.title('regridded')
                     _plt.show()
     elif self.geometry == 'line':
         field_src.data[:] = dataextrap[:, :].transpose()
         field_target = regridme(field_src, field_target)
         if use_locstream:
             data[:, :] = _np.reshape(field_target.data.transpose(),
                                      (self.ny, self.nx))
         else:
             data[:, :] = field_target.data.transpose()[
                 self.jmin:self.jmax + 1, self.imin:self.imax + 1]
     return data
Exemplo n.º 17
0
 def Contour(x, y, z, title):
     X, Y = np.meshgrid(x, y)
     plt.contourf(X, Y, z, 30)
     plt.xlabel("P1 (S->I)")
     plt.ylabel("P3 (R->S)")
     plt.title("Phase diagram of " + str(title))
     plt.colorbar()
     plt.show()
 def PlotArray(self):
     x = y = np.linspace(0,self.dimension-1,self.dimension)
     Y,X = np.meshgrid(x,y)
     plt.contourf(X,Y,self.order_array[:,:],30)
     plt.title("Contour plot of Steady State Concentration Array")
     plt.xlabel("Lattice Position X")
     plt.ylabel("Lattice Position Y")
     plt.colorbar()
     plt.show()
Exemplo n.º 19
0
def normal2(fig, ax):
  # MISSING: Plot the contours of the two-dimensional standard Normal distribution.
  # See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.contour.html
	x, y = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-3, 3, 50))
	z = (np.exp(-x**2 - y**2) / 2.0) / (2.0 * np.pi)
	plt.contourf(x, y, z)
	plt.xlabel('$x$')
	plt.ylabel('$y$')
	plt.axis('equal')
Exemplo n.º 20
0
    def visual(self, Data, no_of_points: int = 1000):
        '''
        '''
        x = zeros((2, 1))

        X, Y = meshgrid(linspace(0, 1, no_of_points),
                        linspace(0, 1, no_of_points))
        # create grid of points
        X1, X2 = array(X.ravel()), array(Y.ravel())
        # vectorize
        Stack = stack((X1, X2), axis=1)
        # left to right stack, columnwise
        empty = zeros(X.shape[0] * X.shape[0])
        # matrix of values

        for i in arange(Stack.shape[0]):
            # run over each coordinate
            x[0, 0], x[1, 0] = Stack[i, 0], Stack[i, 1]
            # input
            Predictions = self.predict(x)
            # predict
            Predictions = array(Predictions[0] >= Predictions[1])
            # create booleans
            if Predictions[0] == True:
                empty[i] = 1
                # assign 1 where true

        Pred = empty.reshape((X.shape[0], X.shape[0]))
        # reshape ready for plotting contour
        import matplotlib.pyplot as plt
        plt.style.use('Solarize_Light2')
        plt.figure()
        # plot figure
        plt.contourf(X, Y, Pred, cmap='cividis', alpha=0.8)
        # plot contour

        plt.scatter(Data.xtrain[0, 0:5],
                    Data.xtrain[1, 0:5],
                    marker='^',
                    c='k',
                    lw=3)
        # plot first half of training set
        plt.scatter(Data.xtrain[0, 5:],
                    Data.xtrain[1, 5:],
                    marker='o',
                    c='w',
                    lw=3)
        # plot second half of training set
        if Data.highamdata:
            plt.savefig('higham_planes.png')
            # save figure
        else:
            plt.savefig('planes.png')
            # save figure
        plt.show()
        return
Exemplo n.º 21
0
    def plot_discontinuity(self,
                           depth,
                           colormap='tomo',
                           res='i',
                           verbose=False):
        """ plot horizontal slices through an ses3d model

    plot_slice(self,depth,colormap='tomo',res='i',verbose=False)

    depth=depth for discontinuity
    colormap='tomo','mono'
    res=resolution of the map, admissible values are: c, l, i, h f

    """

        #- set up a map and colourmap -----------------------------------------
        m = Basemap(projection='merc',
                    llcrnrlat=np.min(grid_lat),
                    urcrnrlat=np.max(grid_lat),
                    llcrnrlon=np.min(grid_lon),
                    urcrnrlon=np.max(grid_lon),
                    lat_ts=20,
                    resolution=res)
        m.drawparallels(np.arange(self.lat_min, self.lat_max, 10.),
                        labels=[0, 0, 0, 0])  #[1,0,0,1])
        m.drawmeridians(np.arange(self.lon_min, self.lon_max, 10.),
                        labels=[0, 0, 0, 0])  #[1,0,0,1])

        m.drawcoastlines()
        m.drawcountries()

        m.drawmapboundary(fill_color=[1.0, 1.0, 1.0])

        model = getattr(self, 'Vs')
        layer = np.argmin(np.abs(self.depth - depth))
        print('True plotting depth is ', self.depth[layer])

        xx, yy = np.meshgrid(self.lon, self.lat)
        x, y = m(xx.T, yy.T)

        topo = np.zeros(np.shape(x))

        for i in range((np.shape(topo)[0])):
            for j in range((np.shape(topo)[1])):
                vel = model[i, j, :]
                ind = np.argmax(np.diff(vel[layer - 4:layer + 4])) + layer - 4
                topo[i, j] = self.depth[ind] + 5.

        minval = np.min(np.min(topo))
        maxval = np.max(np.max(topo))
        contours = np.round(np.linspace(depth - 35., depth + 35., 8))
        plt.contourf(x, y, topo, contours, cmap=plt.cm.get_cmap('jet_r'))
        #plt.pcolor(x,y,self.dvs[:,:,layer],vmin=-0.04, vmax=0.04,cmap=plt.cm.get_cmap('jet_r'))
        plt.colorbar()
        plt.title('Discontinuity at ' + str(depth) + ' km')
def plot_electric(x,y,u,w,beta,a,V,Delta):
    ele = np.zeros([3,len(x),len(y)],dtype=np.complex128)
    for i,xx in enumerate(x):
        for j, yy in enumerate(y):
            ele[:,i,j] = electric_field(xx,yy,u,w,beta,a,V,0,0,Delta)
    abss = (np.abs(ele[0,:,:])**2 + np.abs(ele[1,:,:])**2 + np.abs(ele[2,:,:])**2)**0.5
    X,Y = np.meshgrid(x,y)
    fig = plt.figure()
    plt.contourf(X,Y,abss)
    plt.show()
    return 0
def Decision_Surface(data,
                     target,
                     model,
                     surface=True,
                     probabilities=False,
                     cell_size=.01,
                     size=20):
    # Get bounds
    x_min, x_max = data[data.columns[0]].min(), data[data.columns[0]].max()
    y_min, y_max = data[data.columns[1]].min(), data[data.columns[1]].max()

    # Create a mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, cell_size),
                         np.arange(y_min, y_max, cell_size),
                         sparse=True)
    meshed_data = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])

    # Add interactions
    for i in range(data.shape[1]):
        if i <= 1:
            continue

        meshed_data = np.c_[meshed_data, np.power(xx.ravel(), i)]

    if model != None:
        # Predict on the mesh
        if probabilities:
            Z = model.predict_proba(meshed_data)[:, 1].reshape(xx.shape)
        else:
            Z = model.predict(meshed_data).reshape(xx.shape)

    # Plot mesh and data
    if data.shape[1] > 2:
        plt.title("humor^(" + str(range(1, data.shape[1])) +
                  ") and number_pets")
    else:
        plt.title("humor and number_pets")
    plt.xlabel(data.columns[random_column0])
    plt.ylabel(data.columns[random_column1])
    if surface and model != None:
        if probabilities:
            cs = plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.4)
        else:
            cs = plt.contourf(xx,
                              yy,
                              Z,
                              levels=[-1, 0, 1],
                              cmap=plt.cm.coolwarm,
                              alpha=0.4)
    color = ["blue" if t == 0 else "red" for t in target]
    plt.scatter(data[data.columns[0]],
                data[data.columns[1]],
                color=color,
                s=size)
Exemplo n.º 24
0
def contourplot(objfun, xmin, xmax, ymin, ymax, ncontours=50, fill=True):
    x = np.linspace(xmin, xmax, 200)
    y = np.linspace(ymin, ymax, 200)

    X, Y = np.meshgrid(x,y)
    Z = objfun(X,Y)
    if fill:
        plt.contourf(X,Y,Z,ncontours); # plot the contours
    else:
        plt.contour(X,Y,Z,ncontours); # plot the contours
    plt.scatter(1,1,marker="x",s=50,color="r");  # mark the minimum
Exemplo n.º 25
0
def contour_plot(fig_dims, Z, T, tc, L, N, fname):
    fig = plt.figure(figsize=fig_dims)
    x = np.linspace(T * (tc - 1), T * tc, N)
    y = np.linspace(0, L, N)
    Y, X = np.meshgrid(x, y)
    plt.contourf(X, Y, Z, cmap=cm.viridis)
    plt.ylabel('t (s)')
    plt.xlabel('z (cm)')
    plt.colorbar()
    fname = "plots/%s" % (fname)
    plt.savefig(fname, dpi=600, bbox_inches='tight')
Exemplo n.º 26
0
def potential(x_axis,
              y_axis,
              cbar,
              x_label,
              y_label,
              cbar_label,
              int_pol,
              colorMap,
              xmin=None,
              xmax=None,
              ymin=None,
              ymax=None,
              plot=None):
    """A general plotter allowing for the plotting of a heatmap(primarily used
       here for potential function) which takes in relevant data about the
       graph. It also allows for the option of overlaying either a quiver or a
       streamline plot, or not!

    Parameters:
    x_axis, y_axis : The corresponding x and y axis data lists of a plot
    cbar: The heatmap list data which usually corresponds to x and y axis
    x_label, y_label, : The x, y and z label of the graph       dtype = string
    cbar_label : The colourbar label                            dtype = string
    int_pol: The colour interpolation of the heatmap            dtype = integer
    colorMap: The style and colour of heatmap                   dtype = string
    xmin, xmax: The minimum and maximum value of the x-axis
    ymin, ymax: The minimum and maximum value of the y-axis
    plot: "quiver", "stream" allowing for the overlay of quiver or streamline
          plot

    Returns:
    Image : AxesImage
    """
    plt.contourf(x_axis, y_axis, cbar, int_pol, cmap=colorMap)
    cbar_tag = plt.colorbar()
    Z = cbar
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    cbar_tag.set_label(cbar_label, rotation=270)
    cbar_tag.set_clim(-1000.0, 1000.0)
    E = np.gradient(Z)
    E = E / np.sqrt(E[0]**2 + E[1]**2)
    if plot is not None:
        if plot == "quiver":
            print("\nQuiver plot:")
            plt.quiver(x_axis, y_axis, E[1], E[0])
        if plot == "stream":
            print("\nStreamline Plot:")
            plt.streamplot(x_axis, y_axis, -E[1], -E[0], color='black')
    if xmin is not None and xmax is not None:
        plt.xlim(xmin, xmax)
    if ymin is not None and ymax is not None:
        plt.ylim(ymin, ymax)
    plt.show()
Exemplo n.º 27
0
 def plot(self,key='AOD'):
     """
     Create a plot of a variable over the ORACLES study area. 
     
     Parameters
     ----------
     key : string
     See names for available datasets to plot.
     
     Modification history
     --------------------
     Written: Michael Diamond, 08/16/2016, Seattle, WA
     Modified: Michael Diamond, 08/21/2016
        -Added ORACLES routine flight plan, Walvis Bay (orange), and Ascension Island
     Modified: Michael Diamond, 09/02/2016, Swakopmund, Namibia
         -Updated flight track
     """
     plt.clf()
     size = 16
     font = 'Arial'
     m = Basemap(llcrnrlon=self.lon.min(),llcrnrlat=self.lat.min(),urcrnrlon=self.lon.max(),\
     urcrnrlat=self.lat.max(),projection='merc',resolution='i')
     m.drawparallels(np.arange(-180,180,5),labels=[1,0,0,0],fontsize=size,fontname=font)
     m.drawmeridians(np.arange(0,360,5),labels=[1,1,0,1],fontsize=size,fontname=font)
     m.drawmapboundary(linewidth=1.5)        
     m.drawcoastlines()
     m.drawcountries()
     m.drawmapboundary(fill_color='steelblue')
     m.fillcontinents(color='floralwhite',lake_color='steelblue',zorder=0)
     if key == 'AOD':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
         cbar = m.colorbar()
         cbar.ax.tick_params(labelsize=size-2) 
         cbar.set_label('[%s]' % self.units['%s' % key],fontsize=size,fontname=font)
     elif key == 'ATYP':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
         plt.contourf(np.array(([5,1],[3,2])),cmap=self.colors['%s' % key],levels=[0,1,2,3,4,5])
         cbar = m.colorbar(ticks=[0,1,2,3,4,5])
         cbar.ax.set_yticklabels(['Sea Salt','Sulphate','Organic C','Black C','Dust'])
         cbar.ax.tick_params(labelsize=size-2) 
     else:
         print('Error: Invalid key. Check names for available datasets.')
     m.scatter(14.5247,-22.9390,s=250,c='orange',marker='D',latlon=True)
     m.scatter(-14.3559,-7.9467,s=375,c='c',marker='*',latlon=True)
     m.scatter(-5.7089,-15.9650,s=375,c='chartreuse',marker='*',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='w',linewidth=5,linestyle='dashed',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='k',linewidth=3,linestyle='dashed',latlon=True)
     plt.title('%s from MSG SEVIRI on %s/%s/%s at %s UTC' % \
     (self.names['%s' % key],self.month,self.day,self.year,self.time),fontsize=size+4,fontname=font)
     plt.show()
def plot_intensity_sphere_overlap(theta, phi, rho_0x, rho_0y, rho, w, n_0, P):
    """ plot intensity profile and sphere outline"""
    # theta - sphere theta coordinate, array
    # phi - sphere phi coordinate, array
    # rho_0x - beam x displacement, scalar
    # rho_0y - beam y displacement, scalar
    # rho - sphere diameter, scalar

    intensity = LG_01_Intensity_sphere_coordinate(theta, phi, rho_0x, rho_0y,
                                                  rho, w, n_0, P)

    cartesian_coordinates = spherical_to_cartesian_coordinates(
        5 * rho, theta, phi)
    x = cartesian_coordinates['x']
    y = cartesian_coordinates['y']

    #x = np.linspace(-3 * rho, 3 * rho, 300)
    #y = np.linspace(-3 * rho, 3 * rho, 300)

    plt.contourf(x * 10**6,
                 y * 10**6,
                 intensity / np.max(intensity),
                 500,
                 cmap='Reds')
    cbar = plt.colorbar()

    cbar.set_ticks([0, 0.2, 0.4, 0.6, 0.8, 1])

    plt.xlabel('x(um)', fontsize=20)
    plt.ylabel('y(um)', fontsize=20)
    plt.xlim(-120, 120)
    plt.ylim(120, -120)
    '''
    plt.figure("beam_sphere_overlap_pcolormesh")
    plt.clf()
    plt.pcolormesh(x, y, intensity)
    '''
    # make sure coordiantes not distorted
    axes = plt.gca()
    axes.set_aspect('equal')

    sphere_outline = plt.Circle((0, 0),
                                radius=rho,
                                facecolor='None',
                                edgecolor='k')

    axes.add_artist(sphere_outline)

    #plt.figure("beam_sphere_overlap_surf")

    #plt.su
    return
Exemplo n.º 29
0
def simple_plot(resource, variable=None, output=None):
    output = output or 'plot.png'
    ds = Dataset(resource)
    values = ds.variables[variable]
    fig = plt.figure(figsize=(20, 10))
    ax = plt.axes(projection=ccrs.PlateCarree())
    plt.contourf(values[0, :, :])
    ax.stock_img()
    ax.coastlines()
    plt.colorbar()
    fig.savefig(output)
    plt.close()
    return output
Exemplo n.º 30
0
	def read_2d_obc(self,dirin,obcfile,step=0,orientation='NS',precision='single',ntimes=12):
		filein = dirin + obcfile
		self.ntime = ntimes
		# load data
		if precision == 'single':
			data_raw = np.fromfile(filein,'>f')
		elif precision == 'double':
			data_raw = np.fromfile(filein,'>d')

		# reshape on dims
		if orientation == 'NS':
			data_compact = np.reshape(data_raw,[self.ntime,self.nz,self.nyNS_total])
		elif orientation == 'EW':
			data_compact = np.reshape(data_raw,[self.ntime,self.nz,self.nyEW_total])

		del data_raw
		## split in faces
		if orientation == 'NS':
			data_f1 = data_compact[:,:,:self.nyNS_end[0]]
			data_f2 = data_compact[:,:,self.nyNS_end[0]:self.nyNS_end[1]]
			data_f3 = data_compact[:,:,self.nyNS_end[1]:self.nyNS_end[2]]
			data_f4 = data_compact[:,:,self.nyNS_end[2]:self.nyNS_end[3]]
			data_f5 = data_compact[:,:,self.nyNS_end[3]:self.nyNS_end[4]]
		elif orientation == 'EW':
			data_f1 = data_compact[:,:,:self.nyEW_end[0]]
			data_f2 = data_compact[:,:,self.nyEW_end[0]:self.nyEW_end[1]]
			data_f3 = data_compact[:,:,self.nyEW_end[1]:self.nyEW_end[2]]
			data_f4 = data_compact[:,:,self.nyEW_end[2]:self.nyEW_end[3]]
			data_f5 = data_compact[:,:,self.nyEW_end[3]:self.nyEW_end[4]]

		del data_compact

		plt.figure()
		plt.subplot(151)
		if data_f1.shape[-1] != 0:
			plt.contourf(self.mask_invalid_data(data_f1[step,:]))
		plt.subplot(152)
		if data_f2.shape[-1] != 0:
			plt.contourf(self.mask_invalid_data(data_f2[step,:]))
		plt.subplot(153)
		if data_f3.shape[-1] != 0:
			plt.contourf(self.mask_invalid_data(data_f3[step,:]))
		plt.subplot(154)
		if data_f4.shape[-1] != 0:
			plt.contourf(self.mask_invalid_data(data_f4[step,:]))
		plt.subplot(155)
		if data_f5.shape[-1] != 0:
			plt.contourf(self.mask_invalid_data(data_f5[step,:]))
		plt.show()

		return None
Exemplo n.º 31
0
    def plot_bidensity(self):
        """Plot bivariate density.

        """
        ndots = 100
        xgrid = np.linspace(-2, 2, ndots)
        ygrid = np.linspace(-2, 2, ndots)
        xgrid, ygrid = np.meshgrid(xgrid, ygrid)
        data = np.vstack((xgrid.flatten(), ygrid.flatten())).T
        zvalues = self.pdf(data).reshape((ndots, ndots))
        plt.contourf(xgrid, ygrid, zvalues)
        plt.axis('square')
        plt.title(self.get_name())
        plt.show()
Exemplo n.º 32
0
    def wind_radar_affine(self):
        '''
        功能是生成仿射,并保存。
        把函数直接当属性用的方法:
        '''
        x = np.round(np.linspace(self.stg_X[0], self.stg_X[1], self.pixel[0]),
                     4)
        y = np.round(np.linspace(self.stg_Y[0], self.stg_Y[1], self.pixel[1]),
                     4)
        [X, Y] = np.meshgrid(x, y)

        # 得把时间传进来
        start_time = self.real_time
        end_time = self.real_time + self.duration
        self.time_split = 3  # (end_time - start_time)/self.interval

        for i in range(self.time_split):
            ptime = self.real_time + (i + 1) * interval
            Z = self.read_json_data(self.real_time)  # 只读取此刻真实的radar.
            feng_x = self.read_nc_data('U', ptime)
            feng_y = self.read_nc_data('V', ptime)

            model = AffineModel()
            fx, fy = model(feng_x, feng_y)

            cmaps = colors.LinearSegmentedColormap.from_list('mylist',
                                                             self.colors_sys,
                                                             N=6)
            fig = pb.gcf()
            fig.set_size_inches(4, 4)
            X += fx * 1  # 这里是interval,按小时计算的interval,数值预报默认是1小时出
            Y += fy * 1
            pb.contourf(X, Y, Z, radar_sys, cmap=cmaps, extend='both')  # 循环的生成
            pb.xlim(self.stg_X[0], self.stg_X[1])
            pb.ylim(self.stg_Y[0], self.stg_Y[1])
            pb.gca().xaxis.set_major_locator(plt.NullLocator())
            pb.gca().yaxis.set_major_locator(plt.NullLocator())
            pb.subplots_adjust(top=1,
                               bottom=0,
                               right=1,
                               left=0,
                               hspace=0,
                               wspace=0)
            pb.margins(0, 0)
            affine_image_path = self.save_affine_path + self.real_time + ptime + 'affine' + '.png'
            fig.savefig(affine_image_path,
                        format='png',
                        transparent=True,
                        dpi=200,
                        pad_inches=0)
Exemplo n.º 33
0
def plot_decision_boundary(pred_func):
    # Set min and max values and give it some padding
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
Exemplo n.º 34
0
def plot_solution(problem_data, solution):
    from numpy import linspace
    from matplotlib.pylab import contour, colorbar, contourf, xlabel, ylabel, title, show
    from matplotlib.mlab import griddata

    print(" * Preparing for plotting...")
    NN = problem_data["NN"]

    # Extract node coordinates seperately for plotting
    x, y = [0] * NN, [0] * NN
    for i, node in enumerate(problem_data["nodes"]):
        x[i] = node[0]
        y[i] = node[1]

    # Refine the contour plot mesh for a "smoother" image, by generating a
    # 200*200 grid
    xi = linspace(min(x), max(x), 200)
    yi = linspace(min(y), max(y), 200)

    # Approximate the mid values from neighbors
    zi = griddata(x, y, solution, xi, yi)

    print(" * Plotting...")
    # Plot the contour lines with black
    contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
    # Plot the filled contour plot
    plot = contourf(xi, yi, zi, 15, antialiased=True)

    colorbar(plot, format="%.3f").set_label("T")
    xlabel('X')
    ylabel('Y')
    title("Contour plot of T values for {0}".format(problem_data["title"]))

    show()
Exemplo n.º 35
0
def Decision_Surface(data, target, model, surface=True, probabilities=False, cell_size=.01):
    # Get bounds
    x_min, x_max = data[data.columns[0]].min(), data[data.columns[0]].max()
    y_min, y_max = data[data.columns[1]].min(), data[data.columns[1]].max()
    
    # Create a mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, cell_size), np.arange(y_min, y_max, cell_size))
    meshed_data = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])
    
    # Add interactions
    for i in range(data.shape[1]):
        if i <= 1:
            continue
        
        meshed_data = np.c_[meshed_data, np.power(xx.ravel(), i)]

    if model != None:
        # Predict on the mesh
        if probabilities:
            Z = model.predict_proba(meshed_data)[:, 1].reshape(xx.shape)
        else:
            Z = model.predict(meshed_data).reshape(xx.shape)
    
    # Plot mesh and data
    if data.shape[1] > 2:
        plt.title("humor^(" + str(range(1,data.shape[1])) + ") and number_pets")
    else:
        plt.title("humor and number_pets")
    plt.xlabel("humor")
    plt.ylabel("number_pets")
    if surface and model != None:
        cs = plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.4)
    color = ["blue" if t == 0 else "red" for t in target]
    plt.scatter(data[data.columns[0]], data[data.columns[1]], color=color)
Exemplo n.º 36
0
def plot(AB_final,lams,lamp2,title):
    X,Y = np.meshgrid(lams,lamp2)
    Z = AB_final
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    plt.title(title)
    ax.set_xlabel(r'$\lambda_p(\mu m)$')
    ax.set_ylabel(r'$\lambda_s(\mu m)$')
    ax.set_zlabel(r'$P_{idler}(dBm)$')

    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
    
    fig = plt.figure()
    axi = plt.contourf(X,Y,Z, cmap=cm.jet)
    plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    plt.xlabel(r'$\lambda_p(\mu m)$')
    plt.ylabel(r'$\lambda_s(\mu m)$')
    plt.title(title)
    fig.colorbar(axi, shrink=0.5, aspect=5)
    plt.show()
    return 0
Exemplo n.º 37
0
def Decision_Surface(X, target, model, cell_size=.01, surface=True, points=True):
    # Get bounds
    x_min, x_max = X[:, 0].min(), X[:, 0].max()
    y_min, y_max = X[:, 1].min(), X[:, 1].max()
    
    # Create a mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, cell_size), np.arange(y_min, y_max, cell_size))
    meshed_data = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])
    
    # Add interactions
    for i in range(X.shape[1]):
        if i <= 1:
            continue
        
        meshed_data = np.c_[meshed_data, np.power(xx.ravel(), i)]

    Z_flat = model.predict(meshed_data)
    Z = Z_flat.reshape(xx.shape)

    if surface:
        cs = plt.contourf(xx, yy, Z, color=colorizer(Z_flat))
    
    if points:
        plt.scatter(X[:, 0], X[:, 1], color=colorizer(target), linewidth=0, s=20)
    
    plt.xlabel("Feature 1",fontsize=20)
    plt.ylabel("Feature 2",fontsize=20)
    plt.show()
Exemplo n.º 38
0
def decision_surface(data, target, model, surface=True, probabilities=False, cell_size=0.01):
    plt.rcParams["figure.figsize"] = [10.0, 10.0]

    # Get bounds
    x_min, x_max = data[data.columns[0]].min(), data[data.columns[0]].max()
    y_min, y_max = data[data.columns[1]].min(), data[data.columns[1]].max()

    # Create a mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, cell_size), np.arange(y_min, y_max, cell_size))
    meshed_data = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])

    if model != None:
        # Predict on the mesh
        if probabilities:
            Z = model.predict_proba(meshed_data)[:, 1].reshape(xx.shape)
        else:
            Z = model.predict(meshed_data).reshape(xx.shape)

    # Plot mesh and data
    plt.title("Decision Surface")

    plt.xlabel(data.columns[0])
    plt.ylabel(data.columns[1])

    if surface and model != None:
        cs = plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm_r, alpha=0.4)

    color = ["red" if t == 0 else "blue" for t in target]

    plt.scatter(data[data.columns[0]], data[data.columns[1]], color=color)
    plt.show()
Exemplo n.º 39
0
def contour(X,Y,Z, 
           extent=None, vrange=None, levels=None, extend='both', 
           inaxis=None,
           cmap=None, addcolorbar=True, clabel=None,
           smooth=True, smoothlen=None):
    '''Build a super fancy contour image'''
    
    # Build up some nice ranges and levels to be plotted 
    XX, YY = _getmesh(X,Y,Z)
    extent = _getextent(extent, XX, YY)
    vrange = _getvrange(vrange, XX,YY,Z, inaxis=inaxis)
    levels = _getlevels(levels, vrange)
    cmap   = _getcmap(cmap)
    
    # Smooth if needed
    if smooth:
        X,Y,Z = _smooth(X,Y,Z, smoothlen)
    
    cs = pylab.contourf(X, Y, Z, levels,
                       vmin=vrange[0], vmax=vrange[1],
                       extent=extent, extend='both',
                       cmap=cmap)
    ccs = pylab.contour(X, Y, Z, levels, vmin=vrange[0], vmax=vrange[1],
                        cmap=cmap)
    
    # setup a colorbar, add in the lines, and then return it all out.
    if addcolorbar:
        cb = colorbar(cs, ccs, levels=levels, clabel=clabel)
        return cs, ccs, cb
    
    return cs, ccs
Exemplo n.º 40
0
def time_freq_plot(t, freqs, data, coefs, xunits='s', yunits=''):
    if xunits == 'ms':
        t = 1e3 * t
    fig = plt.figure(figsize=(12, 6))
    plt.subplots_adjust(wspace=.8, hspace=.5, bottom=.2)
    # signal plot
    plt.subplot2grid((3, 7), (0, 0), colspan=6)
    plt.plot(t, data)
    plt.ylabel(yunits)
    plt.xlim([t[0], t[-1]])
    # time frequency power plot
    plt.subplot2grid((3, 7), (1, 0), rowspan=2, colspan=6)
    c = plt.contourf(t, freqs, coefs, cmap='PRGn', aspect='auto')
    plt.xlabel('time (' + xunits + ')')
    plt.ylabel('frequency (Hz)')
    # mean power plot over intervals
    plt.subplot2grid((3, 7), (1, 6), rowspan=2)
    plt.xlabel('power')
    # max of power over intervals
    plt.subplot2grid((3, 8), (1, 7), rowspan=2)
    plt.barh(freqs, np.power(coefs,2).mean(axis=1),\
             label='mean', height=freqs[-1]-freqs[-2])
    # plt.plot(np.power(coefs,2).max(axis=1), freqs,\
    #          label='max.')
    plt.xlabel(' power')
    plt.legend(prop={'size': 'small'}, loc=(0.1, 1.1))
    return fig
Exemplo n.º 41
0
def plot_contour(z,x,y,title="TITLE",xtitle="",ytitle="",xrange=None,yrange=None,plot_points=0,contour_levels=20,
                 cmap=None,cbar=True,fill=False,cbar_title="",show=1):

    fig = plt.figure()

    if fill:
        fig = plt.contourf(x, y, z.T, contour_levels, cmap=cmap, origin='lower')
    else:
        fig = plt.contour( x, y, z.T, contour_levels, cmap=cmap, origin='lower')

    if cbar:
        cbar = plt.colorbar(fig)
        cbar.ax.set_ylabel(cbar_title)


    plt.title(title)
    plt.xlabel(xtitle)
    plt.ylabel(ytitle)

    # the scatter plot:
    if plot_points:
        axScatter = plt.subplot(111)
        axScatter.scatter( np.outer(x,np.ones_like(y)), np.outer(np.ones_like(x),y))

    # set axes range
    plt.xlim(xrange)
    plt.ylim(yrange)

    if show:
        plt.show()

    return fig
Exemplo n.º 42
0
    def plotModel2D(self,X=[],Y=[],xLabel="",yLabel="",title="",fName=""):
        #fig = plt.figure(figsize=(6,4),dpi=100)
        plt.close()
        
        # 真値のプロット(クラスごとにマーカーを変更)
        plt.plot(X[Y[:,0]==0,0],X[Y[:,0]==0,1],'cx',markersize=14,label="ラベル0")
        plt.plot(X[Y[:,0]==1,0],X[Y[:,0]==1,1],'m.',markersize=14,label="ラベル1")

        # 予測値のメッシュの計算
        X1,X2 = plt.meshgrid(plt.linspace(np.min(X[:,0]),np.max(X[:,0]),50),plt.linspace(np.min(X[:,1]),np.max(X[:,1]),50))
        Xmesh = np.hstack([np.reshape(X1,[-1,1]),np.reshape(X2,[-1,1])])
        Pmesh,_,_ = self.predict(Xmesh)
        Pmesh = np.reshape(Pmesh,X1.shape)

        # 予測値のプロット
        CS = plt.contourf(X1,X2,Pmesh,linewidths=2,cmap="bwr",alpha=0.3,vmin=0,vmax=1)

        # カラーバー
        CB = plt.colorbar(CS)
        CB.ax.tick_params(labelsize=14)

        # 各軸の範囲とラベルの設定
        plt.xlim([np.min(X[:,0]),np.max(X[:,0])])
        plt.ylim([np.min(X[:,1]),np.max(X[:,1])])
        plt.title(title,fontsize=14)
        plt.xlabel(xLabel,fontsize=14)
        plt.ylabel(yLabel,fontsize=14)
        plt.legend()

        # グラフの表示またはファイルへの保存
        if len(fName):
            plt.savefig(fName)
        else:
            plt.show()
Exemplo n.º 43
0
def time_freq_plot(t, freqs, data, coefs):
    """
    a plot to illustrate the output of the wavelet analysis
    """
    dt = t[1] - t[0]
    import matplotlib.pylab as plt

    fig = plt.figure(figsize=(8, 5))
    plt.subplots_adjust(wspace=.8, hspace=.5, bottom=.2)
    # signal plot
    plt.subplot2grid((3, 8), (0, 0), colspan=6)
    plt.plot(1e3 * t, data, 'k-', lw=2)
    plt.ylabel('signal')
    plt.xlim([1e3 * t[0], 1e3 * t[-1]])
    # time frequency power plot
    ax1 = plt.subplot2grid((3, 8), (1, 0), rowspan=2, colspan=6)
    c = plt.contourf(1e3 * t, freqs, coefs, cmap='PRGn', aspect='auto')
    plt.xlabel('time (ms)')
    plt.ylabel('frequency (Hz)')
    # inset with legend
    acb = plt.axes([.4, .4, .02, .2])
    plt.colorbar(c, cax=acb, label='coeffs (a.u.)', ticks=[-1, 0, 1])
    # mean power plot over intervals
    plt.subplot2grid((3, 8), (1, 6), rowspan=2)
    plt.barh(freqs, np.power(coefs, 2).mean(axis=1) * dt)
    plt.xticks([])
    plt.xlabel(' mean \n power \n (a.u.)')
    # max of power over intervals
    plt.subplot2grid((3, 8), (1, 7), rowspan=2)
    plt.barh(freqs, np.power(coefs, 2).max(axis=1) * dt)
    plt.xticks([])
    plt.xlabel(' max. \n power \n (a.u.)')
    return fig
Exemplo n.º 44
0
def Decision_Surface(X, target, model, cell_size=.01, surface=True, points=True):
    # Get bounds
    x_min, x_max = X[:, 0].min(), X[:, 0].max()
    y_min, y_max = X[:, 1].min(), X[:, 1].max()
    
    # Create a mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, cell_size), np.arange(y_min, y_max, cell_size))
    meshed_data = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()])
    
    # Add interactions
    for i in range(X.shape[1]):
        if i <= 1:
            continue
        
        meshed_data = np.c_[meshed_data, np.power(xx.ravel(), i)]

    Z_flat = model.predict(meshed_data)
    Z = Z_flat.reshape(xx.shape)
    
    # Plot mesh and data
    plt.title("humor and number_pets")
    plt.xlabel("humor")
    plt.ylabel("number_pets")
    
    if surface:
        cs = plt.contourf(xx, yy, Z, color=colorizer(Z_flat))
    
    if points:
        plt.scatter(X[:, 0], X[:, 1], color=colorizer(target), linewidth=0, s=20)
    
    plt.xlabel("Feature 1")
    plt.xlabel("Feature 2")
    plt.show()
Exemplo n.º 45
0
def diffDensity(fig, F2, F3, Trange):
    T1 = copy.deepcopy(Trange)
    T2 = copy.deepcopy(Trange)
    X, Y = numpy.meshgrid(T1, T2)
    p2 = []
    p3 = []
    for tau in Trange:
        p2.append(F2.pdf(tau))
        p3.append(F3.pdf(tau))
    p2mat = numpy.matrix(p2)
    p3mat = numpy.matrix(p3)
    pp2 = p2mat.T * p2mat
    pp3 = p3mat.T * p3mat
    PXP = numpy.array(numpy.log(pp3) - numpy.log(pp2))
    # norm = plt.cm.colors.Normalize(vmin=-0.8,vmax=0.8)
    levels = numpy.arange(-2.0, .1, .1)
    cmap = plt.cm.get_cmap("PiYG")
    cmap.set_under(color='red', alpha=0.3)
    cmap.set_over(color='red', alpha=0.3)
    cset = plt.contourf(X,
                        Y,
                        PXP,
                        levels=numpy.array([-10.0, 0, .8]),
                        colors=('r', 'g'),
                        alpha=.3)  #plt.cm.get_cmap(cmap,2))
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    levels = numpy.arange(-10, .8, .1)
    cs2 = plt.contour(X, Y, PXP, levels=levels, colors='k', alpha=.2)
    plt.clabel(cs2, levels[91:], fontsize=9, inline=1)
    # plt.colorbar(cset)
    plt.xlabel("First Opening Time $\\tau_1$")
    plt.ylabel("Second Opening Time $\\tau_2$")
    plt.title(
        "Test Statistic Comparing Models as a Function of Two Observations")
    plt.show()
Exemplo n.º 46
0
def plot_svc(X, y, mysvc, bounds=None, grid=50):
    if bounds is None:
        xmin = np.min(X[:, 0], 0)
        xmax = np.max(X[:, 0], 0)
        ymin = np.min(X[:, 1], 0)
        ymax = np.max(X[:, 1], 0)
    else:
        xmin, ymin = bounds[0], bounds[0]
        xmax, ymax = bounds[1], bounds[1]
    aspect_ratio = (xmax - xmin) / (ymax - ymin)
    xgrid, ygrid = np.meshgrid(np.linspace(xmin, xmax, grid),
                              np.linspace(ymin, ymax, grid))
    plt.gca(aspect=aspect_ratio)
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.xticks([])
    plt.yticks([])
    plt.hold(True)
    plt.plot(X[y == 1, 0], X[y == 1, 1], 'bo')
    plt.plot(X[y == -1, 0], X[y == -1, 1], 'ro')
    
    box_xy = np.append(xgrid.reshape(xgrid.size, 1), ygrid.reshape(ygrid.size, 1), 1)
    if mysvc is not None:
        scores = mysvc.decision_function(box_xy)
    else:
        print 'You must have a valid SVC object.'
        return None;
    
    CS=plt.contourf(xgrid, ygrid, scores.reshape(xgrid.shape), alpha=0.5, cmap='jet_r')
    plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[0], colors='k', linestyles='solid', linewidths=1.5)
    plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[-1,1], colors='k', linestyles='dashed', linewidths=1)
    plt.plot(mysvc.support_vectors_[:,0], mysvc.support_vectors_[:,1], 'ko', markerfacecolor='none', markersize=10)
    CB = plt.colorbar(CS)
Exemplo n.º 47
0
def Plot2DwSVM(datax, datay):
    """
    plot data and corresponding SVM results.
    """
    clf = svm.SVC()
    clf.fit(datax, datay)
    step = 0.02
    x_min, x_max = datax[:,0].min(), datax[:,0].max()
    y_min, y_max = datax[:,1].min(), datax[:,1].max()
    xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, step), numpy.arange(y_min, y_max, step))
    Z = clf.decision_function(numpy.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    pylab.contourf(xx, yy, Z, 10, cmap=pylab.cm.Oranges)
    pylab.scatter(datax[datay == 1,0], datax[datay == 1,1], c='b', s=50)
    pylab.scatter(datax[datay != 1,0], datax[datay != 1,1], c='r', s=50)
    pylab.show()
def plot(points, col):
    n = 256
    x = np.linspace(-100, 100, n)
    y = np.linspace(-100, 100, n)
    X, Y = np.meshgrid(x, y)
    
    xs = []
    ys = []
    
    pl.contourf(X, Y, fun([X, Y]), 8, alpha=.75, cmap='jet')
    pl.contour(X, Y, fun([X, Y]), 8, colors='black', linewidth=.5) 
    
    for i in range(len(points)):
        xs.append(points[i][0])
        ys.append(points[i][1])
    
    pl.plot(xs, ys, marker='o', linestyle='--', color=str(col), label='Square')
Exemplo n.º 49
0
def plot_decision_surface(axes, clf, X, Y):
    import numpy as np
    h=.02 # step size in the mesh
    # create a mesh to plot in
    x_min, x_max = X[:,0].min()-1, X[:,0].max()+1
    y_min, y_max = X[:,1].min()-1, X[:,1].max()+1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    axes.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z)
    pylab.axis('off')

    # Plot also the training points
    pylab.scatter(X[:,0], X[:,1], c=Y)
Exemplo n.º 50
0
def plot(points):
    '''
        Plotting 2D function and way search
    '''
    n = 256
    x = np.linspace(-12, 12, n)
    y = np.linspace(-12, 12, n)
    X, Y = np.meshgrid(x, y)
    
    xs = []
    ys = []
    
    pl.contourf(X, Y, fun([X, Y]), 8, alpha=.75, cmap='jet')
    C = pl.contour(X, Y, fun([X, Y]), 8, colors='black', linewidth=.5) 
    
    for i in range(len(points)):
        xs.append(points[i][0])
        ys.append(points[i][1])
    
    pl.plot(xs, ys, marker='o', linestyle='--', color='r', label='Square')            
Exemplo n.º 51
0
def plot(points):
    """
        Plotting 2D function and way search
    """
    n = 256
    x = np.linspace(-12, 12, n)
    y = np.linspace(-12, 12, n)
    X, Y = np.meshgrid(x, y)

    xs = []
    ys = []

    pl.contourf(X, Y, fun([X, Y]), 8, alpha=0.75, cmap="jet")
    C = pl.contour(X, Y, fun([X, Y]), 8, colors="black", linewidth=0.5)

    for i in range(len(points)):
        xs.append(points[i][0])
        ys.append(points[i][1])

    pl.plot(xs, ys, marker="o", linestyle="--", color="r", label="Square")
def plt_decision_regions(X, y, classifier, resolution = 0.02):
	markers = ('s', 'x', 'o', '^', 'v')
	colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
	cmap = ListedColormap(colors[:len(np.unique(y))])

	#plot decision surface
	x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
	x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
	xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), 
		np.arange(x2_max, x2_max, resolution))
	z = classifier.predict(np.array([xx1.reval(), xx2.reval()]).T)
	z = z.reshape(xx1.shape)
	plt.contourf(xx1, xx2, z, alpha = 0.4, cmap = cmap)
	plt.xlim(xx1.min(), xx1.max())
	plt.ylim(xx2.min(), xx2.max())

	#plot class samples
	for idx, c1 in enumerate(np.unique(y)):
		plt.scatter(x = X[y == c1, 0], y = X[y == c1, 1], 
			alpha = 0.8, c = cmap(idx), marker = markers[idx], label = c1)
Exemplo n.º 53
0
def plot_decision_surface(axes, clf, X, Y):
    import matplotlib.pylab as pylab
    import numpy as np
    # step size in the mesh
    h = (np.max(X, axis=0) - np.min(X, axis=0)) / 100.0
    # create a mesh to plot in
    x_min = np.min(X, axis=0) - 1
    x_max = np.max(X, axis=0) + 1
    xx, yy = np.meshgrid(np.arange(x_min[0], x_max[0], h[0]),
                         np.arange(x_min[1], x_max[1], h[1]))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pylab.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z, cmap=pylab.cm.Paired)
    #pylab.axis('off')

    # Plot also the training points
    pylab.scatter(X[:,0], X[:,1], c=Y)
Exemplo n.º 54
0
def plot_rough(data=None, use_fb=True, levels=20, colorbars=False):
        if data is None: data = read_rough('rough')
        (x, y) = ('fb_x', 'fb_y') if use_fb else ('x', 'y')
        fig = pl.figure()
        #pos = np.genfromtxt("rough_pos")
        pos = None
        print pos
        for n,signal in enumerate(['psd_x', 'psd_y', 'sum_x', 'sum_y']):
                pl.subplot(2,2,n+1)
                pl.contourf(data[x][:,:,0], data[y][:,:,0], data[signal][:,:,0], levels)
                pl.title(signal)
                pl.axis('equal')
                pl.axis('tight')
                if colorbars:
                        pl.colorbar()

                if pos is not None:
                        pl.axvline(pos[0], alpha=0.3)
                        pl.axhline(pos[1], alpha=0.3)

        fig.show()
Exemplo n.º 55
0
 def plot_mpl(da, U):
     comm = da.getComm()
     rank = comm.getRank()
     scatter, U0 = PETSc.Scatter.toZero(U)
     scatter.scatter(U, U0, False, PETSc.Scatter.Mode.FORWARD)
     if rank == 0:
         try:
             from matplotlib import pylab
         except ImportError:
             PETSc.Sys.Print("matplotlib not available")
         else:
             from numpy import mgrid
             nx, ny, nz = da.sizes
             solution = U0[...].reshape(da.sizes, order='f')
             xx, yy =  mgrid[0:1:1j*nx,0:1:1j*ny]
             pylab.contourf(xx, yy, solution[:, :, nz//2])
             pylab.axis('equal')
             pylab.xlabel('X')
             pylab.ylabel('Y')
             pylab.title('Z/2')
             pylab.show()
     comm.barrier()
Exemplo n.º 56
0
	def perform_extrapolation(self,datasrc,maskfile,maskvar,missing_value,drown):
		# 2.1 read mask or compute it
		if maskvar is not None:
			mask = _ncdf.read_field(maskfile,maskvar)
			# to do, needs imin/imax_src,...
		else:
			mask = self.compute_mask_from_missing_value(datasrc,missing_value=missing_value)
		# 2.2 mask the source data
		if _np.ma.is_masked(datasrc):
			datasrc = datasrc.data
		datasrc[_np.where(mask == 0)] = self.xmsg
		datamin = datasrc[_np.where(mask == 1)].min()
		datamax = datasrc[_np.where(mask == 1)].max()
		if self.debug:
			datasrc_plt = _np.ma.masked_values(datasrc,self.xmsg)
			_plt.figure() ; _plt.contourf(datasrc_plt[0,:,:],40) ; _plt.title('original') ; _plt.colorbar() 
		# 2.3 perform land extrapolation on reduced variable
		datanorm = self.normalize(datasrc,datamin,datamax,mask)
		if self.debug:
			print(datanorm.min() , datanorm.max(), datamin, datamax)
		datanormextrap = self.drown_field(datanorm,mask,drown)
		dataextrap = self.unnormalize(datanormextrap,datamin,datamax)
		return dataextrap
Exemplo n.º 57
0
def display_fv_solution(grid, field_name, **kwargs):
    fig = plt.figure()
    plt.axes().set_aspect('equal')

    var, = grid.get_cell_fields(field_name)
    cell_nodes = grid.cell_nodes

    plt.contourf(cell_nodes[:, :, 0], cell_nodes[:, :, 1], var, kwargs.get('contour_levels', 15))

    if kwargs.get('show_grid', False):
        plt.plot(cell_nodes[:, :, 0], cell_nodes[:, :, 1], '-', color='black')
        plt.plot(np.transpose(cell_nodes[:, :, 0]), np.transpose(cell_nodes[:, :, 1]), '-', color='black')

    if kwargs.get('mark_cell_centers', False):
        plt.plot(cell_nodes[:, :, 0], cell_nodes[:, :, 1], 'o', color='black')

    if kwargs.get('show', False):
        plt.show()

    f = BytesIO()
    plt.savefig(f)

    return f
Exemplo n.º 58
0
def plot2D(x, y, z, zmin= None, zmax= None, xlim=None, ylim=None, nx = 200, ny = 200):

  if zmin == None:
    zmin = min(z)

  if zmax == None:
    zmax = max(z)

  for i in range(len(z)):
    z[i] = min(z[i], zmax)
    z[i] = max(z[i], zmin)

  xi = np.linspace(min(x), max(x), nx)
  yi = np.linspace(min(y), max(y), ny)
  zi = plt.mlab.griddata(x, y, z, xi, yi)

  plt.contourf(xi, yi, zi, 32, cmap=plt.cm.jet) #, norm=plt.Normalize(zmin, zmax))
  plt.contourf(xi, yi, zi, 32, norm=plt.Normalize(zmin, zmax))
  if 1 == 1:

    if (xlim == None):
      plt.xlim(-6.0, +6.0)
    else:
      plt.xlim(xlim[0], xlim[1]);

    if (ylim == None):
      plt.ylim(-6.0, +6.0)
    else:
      plt.ylim(ylim[0], ylim[1]);

  else:
    plt.xlim(-0.5, +0.5)
    plt.ylim(-0.5, +0.5)


  plt.colorbar()
  plt.show()
Exemplo n.º 59
0
 def plot_teff_logg(self, fig):
     fig.clf()
     ax = fig.add_subplot(111)
     #grid = ax.imshow(self.teff_logg_grid.transpose(),  aspect='auto', extent=(self.teffs.min(), self.teffs.max(), self.loggs.min(), self.loggs.max()))
     #fig.colorbar(grid)
     ax.set_xlabel('Teff')
     ax.set_ylabel('log(g)')
     X, Y = np.meshgrid(self.teffs, self.loggs)
     contours = ax.contourf(X, Y, self.teff_logg_grid)
     fig.colorbar(contours)
     ax.plot([self.teff], [self.logg], 'rx', mew=3, ms=20, label='polyfit')
     ax.plot([self.teff_min], [self.logg_min], 'gx', mew=3, ms=20, label='min')
     ax.set_title('teff = %.2f teff_min = %.2f logg = %.2f logg_min = %.2f' %
                  (self.teff, self.teff_min, self.logg, self.logg_min))
     ax.legend(numpoints=1)