Python matplotlib.pyplot 模块,pcolormesh() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.pcolormesh()

项目:fem    作者:mlp6    | 项目源码 | 文件源码
def play(self, timerange):
        """play an animation

        Strongly recommend not stepping though each timesteps; use some skips!

        :param timerange: range generator of time steps to animate
        """
        import matplotlib.pyplot as plt
        import matplotlib.animation as animation

        fig = plt.figure()

        plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, 0])
        plt.axes().set_aspect('equal')
        plt.gca().invert_yaxis()
        plt.xlabel('Lateral (mm)')
        plt.ylabel('Axial (mm)')

        anim = animation.FuncAnimation(fig, self.animate, frames=timerange,
                                       blit=False)

        plt.show()
项目:crypto-forcast    作者:7yl4r    | 项目源码 | 文件源码
def plotImage(dta, saveFigName):
    plt.clf()
    dx, dy = 1, 1
    # generate 2 2d grids for the x & y bounds
    with np.errstate(invalid='ignore'):
        y, x = np.mgrid[
            slice(0, len(dta)   , dx),
            slice(0, len(dta[0]), dy)
        ]
        z = dta
        z_min, z_max = -np.abs(z).max(), np.abs(z).max()

        #try:
        c = plt.pcolormesh(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max)
        #except ??? as err:  # data not regular?
        #   c = plt.pcolor(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max)
        d = plt.colorbar(c, orientation='vertical')
        lx = plt.xlabel("index")
        ly = plt.ylabel("season length")
        plt.savefig(str(saveFigName))
项目:Machine-Learning-Algorithms    作者:PacktPublishing    | 项目源码 | 文件源码
def show_classification_areas(X, Y, lr):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(30, 25))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm)
    plt.xlabel('X')
    plt.ylabel('Y')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show()
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def rp_timeseries_embedding(ax, data, **kwargs):
        """recurrence plot using pyunicorn
        """
        emb_del = 1
        emb_dim = 10
        # logger.log(loglevel_debug, "rp_timeseries_embedding data", data)
        # make data "strictly" one-dimensional
        data = data.reshape((-1, ))
        rp = RecurrencePlot(time_series = data, tau = emb_del, dim = emb_dim, threshold_std = 1.5)

        plotdata = rp.recurrence_matrix()
        length = plotdata.shape[0]

        xs = np.linspace(0, length, length)
        ys = np.linspace(0, length, length)
        ax.pcolormesh(xs, ys, plotdata, cmap=plt.get_cmap("Oranges"))
        ax.set_xlabel("$n$")
        ax.set_ylabel("$n$")
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_hamming_dist(s,W,brec):
    masks = s[:,0,:].T>0
    x_hat = np.zeros(masks.shape)

    for ii in range(masks.shape[1]):
        Weff = W*masks[:,ii]
        x_hat[:,ii] = np.linalg.inv(np.eye(100)-Weff).dot(brec)

    fig = plt.figure()
    plt.pcolormesh(squareform(pdist(np.sign(x_hat[:,:]).T,metric='hamming'))) #,vmax=.3)
    plt.colorbar()
    plt.ylim([0,x_hat.shape[1]])
    plt.xlim([0,x_hat.shape[1]])

    plt.axes().set_aspect('equal')
    plt.title('Hamming Distance Between Putative FPs')
    plt.ylabel('Time')
    plt.xlabel('Time')

    return fig
项目:speech_ml    作者:coopie    | 项目源码 | 文件源码
def main():
    path_to_data = sys.argv[-1]
    data_type = sys.argv[-2]
    if data_type == '-spec':
        ids, sets, specs, fs, ts = get_cached_data(path_to_data)
        for ident, set_name, spec in zip(ids, sets, specs):
            plt.pcolormesh(ts[:spec.shape[1]], fs[:spec.shape[0]], spec)
            plt.ylabel('Frequency [Hz]')
            plt.xlabel('Time [sec]')

            maxlabel = 'max: ' + str(np.max(spec))
            meanlabel = 'mean: ' + str(np.mean(spec))

            plt.title(','.join([ident, set_name, maxlabel, meanlabel]))
            plt.show()

    else:
        print('only works for spectrograms at the moment')
项目:iota    作者:amaneureka    | 项目源码 | 文件源码
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 pyplot.pcolor and/or pyplot.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 = 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)
项目:hierarchical_rl    作者:wulfebw    | 项目源码 | 文件源码
def make_heat_map(filepath, epoch):
    # convert value image to numeric array
    value_array = get_value_array_from_value_image_file(filepath)
    if value_array is None:
        print 'Value image could not be converted to heatmap'
        return

    # determine output filepath
    run_dir = get_run_directory(filepath)
    output_filepath = os.path.join(run_dir, 'heatmaps', 'value_heatmap_{}.png'.format(epoch))

    # create and save heatmap
    heatmap = plt.pcolormesh(value_array, vmin=-0.25, vmax=1.25)
    plt.colorbar()
    plt.savefig(output_filepath)
    plt.close()
项目:ThinkX    作者:AllenDowney    | 项目源码 | 文件源码
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)
项目:randomforest-density-python    作者:ksanjeevan    | 项目源码 | 文件源码
def check_plot(self):

        X = self.grid[0]
        Y = self.grid[1]
        Z = self.dist

        fig = plt.figure(figsize=(12, 12))
        ax = fig.add_subplot(111)

        vmin = np.min(Z)
        vmax = np.max(Z)
        var = plt.pcolormesh(np.array(X),np.array(Y),np.array(Z), cmap=cm.Greens, vmin=vmin, vmax=vmax)
        plt.colorbar(var, ticks=np.arange(vmin, vmax, (vmax-vmin)/8))
        ax = plt.gca()
        gris = 200.0
        ax.set_facecolor((gris/255, gris/255, gris/255))

        ax.scatter(*zip(*self.data), alpha=.5, c='k', s=10., lw=0)

        plt.xlim(np.min(X), np.max(X))
        plt.ylim(np.min(Y), np.max(Y))
        plt.grid()
        fig.savefig('true_dist_check.png', format='png')
        plt.close()
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def plot_sound_class_by_decending_accuracy(experiment_path):
    config_parser = configparser.ConfigParser()
    config_parser.read(os.path.join(experiment_path, "conf.ini"))
    model_name = config_parser['MODEL']['ModelName']
    y_trues, y_scores = load_predictions(experiment_path)

    y_true = [np.argmax(y_t) for y_t in y_trues]
    y_pred = [np.argmax(y_s) for y_s in y_scores]

    confusion_matrix = metrics.confusion_matrix(y_true, y_pred)

    accuracies = []
    (nb_rows, nb_cols) = confusion_matrix.shape
    for i in range(nb_rows):
        accuracy = confusion_matrix[i][i] / np.sum(confusion_matrix[i,:])
        accuracies.append(accuracy)

    fig = plt.figure()
    plt.title("Sound Class ranked by Accuracy ({})".format(model_name))
    plt.plot(sorted(accuracies, reverse=True))
    plt.ylabel("Accuracy")
    plt.xlabel("Rank")
    # plt.pcolormesh(confusion_matrix, cmap=cmap)
    fig.savefig(os.path.join(experiment_path, "descending_accuracy.png"))
项目:StackedDAE    作者:glrs    | 项目源码 | 文件源码
def make_2d_hist(data, name):
    f = plt.figure()
    X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
    im = plt.pcolormesh(X,Y,data.transpose(), cmap='seismic')
    plt.colorbar(im, orientation='vertical')
#     plt.hexbin(data,data)
#     plt.show()
    f.savefig(pjoin(FLAGS.output_dir, name + '.png'))
    plt.close()

# def make_2d_hexbin(data, name):
#     f = plt.figure()
#     X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
#     plt.hexbin(X, data)
# #     plt.show()
#     f.savefig(pjoin(FLAGS.output_dir, name + '.png'))
项目:fem    作者:mlp6    | 项目源码 | 文件源码
def plot(self, timestep):
        """plot arfidata at specified timestep

        :param timestep: int
        """
        import matplotlib.pyplot as plt

        plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, timestep])
        plt.axes().set_aspect('equal')
        plt.xlabel('Lateral (mm)')
        plt.ylabel('Axial (mm)')
        plt.title('t = {:.2f} ms'.format(self.t[timestep]))
        plt.gca().invert_yaxis()
        plt.show()

        return
项目:fem    作者:mlp6    | 项目源码 | 文件源码
def animate(self, i):
        import matplotlib.pyplot as plt
        plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, i])
        plt.title('t = {:.2f} ms'.format(self.t[i]))
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def phase_diagram_grid(x_vals, y_vals, data,
                            title="Phase diagram",
                            xlabel="Pulse Duration (s)",
                            ylabel="Pulse Amplitude (V)"):
    fig = plt.figure()
    data = data.reshape(len(y_vals), len(x_vals), order='F')
    plt.pcolormesh(x_vals, y_vals, data, cmap="RdGy")
    plt.colorbar()
    plt.title(title, size=16)
    plt.xlabel(xlabel, size=16)
    plt.ylabel(ylabel, size=16)
    return fig
项目:Python-Machine-Learning-Cookbook    作者:PacktPublishing    | 项目源码 | 文件源码
def plot_classifier(classifier, X, y):
    # define ranges to plot the figure 
    x_min, x_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0
    y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 1]) + 1.0

    # denotes the step size that will be used in the mesh grid
    step_size = 0.01

    # define the mesh grid
    x_values, y_values = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))

    # compute the classifier output
    mesh_output = classifier.predict(np.c_[x_values.ravel(), y_values.ravel()])

    # reshape the array
    mesh_output = mesh_output.reshape(x_values.shape)

    # Plot the output using a colored plot 
    plt.figure()

    # choose a color scheme you can find all the options 
    # here: http://matplotlib.org/examples/color/colormaps_reference.html
    plt.pcolormesh(x_values, y_values, mesh_output, cmap=plt.cm.gray)

    # Overlay the training points on the plot 
    plt.scatter(X[:, 0], X[:, 1], c=y, s=80, edgecolors='black', linewidth=1, cmap=plt.cm.Paired)

    # specify the boundaries of the figure
    plt.xlim(x_values.min(), x_values.max())
    plt.ylim(y_values.min(), y_values.max())

    # specify the ticks on the X and Y axes
    plt.xticks((np.arange(int(min(X[:, 0])-1), int(max(X[:, 0])+1), 1.0)))
    plt.yticks((np.arange(int(min(X[:, 1])-1), int(max(X[:, 1])+1), 1.0)))

    plt.show()
项目:bifrost    作者:ledatelescope    | 项目源码 | 文件源码
def save_waterfall_plot(self, waterfall_matrix):
        """Save an image of the waterfall plot using
            thread-safe backend for pyplot, and labelling
            the plot using the header information from the
            ring
        @param[in] waterfall_matrix x axis is frequency and
            y axis is time. Values should be power.
            """
        import matplotlib
        # Use a graphical backend which supports threading
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        plt.ioff()
        print "Interactive mode off"
        print waterfall_matrix.shape
        fig = pylab.figure()
        ax = fig.gca()
        header = self.header
        ax.set_xticks(
            np.arange(0, 1.33, 0.33) * waterfall_matrix.shape[1])
        ax.set_xticklabels(
            header['fch1'] - np.arange(0, 4) * header['foff'])
        ax.set_xlabel("Frequency [MHz]")
        ax.set_yticks(
            np.arange(0, 1.125, 0.125) * waterfall_matrix.shape[0])
        ax.set_yticklabels(
            header['tstart'] + header['tsamp'] * np.arange(0, 1.125, 0.125) * waterfall_matrix.shape[0])
        ax.set_ylabel("Time (s)")
        plt.pcolormesh(
            waterfall_matrix, axes=ax, figure=fig)
        fig.autofmt_xdate()
        fig.savefig(
            self.imagename, bbox_inches='tight')
        plt.close(fig)
项目:Python-first-Practice    作者:MurphyWan    | 项目源码 | 文件源码
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 1.0
    y_min = 0.0; y_max = 1.0

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    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)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="fast")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="slow")
    plt.legend()
    plt.xlabel("bumpiness")
    plt.ylabel("grade")

    plt.savefig("test.png")
项目:jingjuSingingPhraseMatching    作者:ronggong    | 项目源码 | 文件源码
def _pathPlot(self,transcription_gt,path_gt,path):
        '''
        plot ground truth path and decoded path
        :return:
        '''

        ##-- unique transcription and path
        transcription_unique = []
        transcription_number_unique = []
        B_map_unique = np.array([])
        for ii,t in enumerate(self.transcription):
            if t not in transcription_unique:
                transcription_unique.append(t)
                transcription_number_unique.append(ii)
                if not len(B_map_unique):
                    B_map_unique = self.B_map[t]
                else:
                    B_map_unique = np.vstack((B_map_unique,self.B_map[t]))

        trans2transUniqueMapping = {}
        for ii in range(len(self.transcription)):
            trans2transUniqueMapping[ii] = transcription_unique.index(self.transcription[ii])

        path_unique = []
        for ii in range(len(path)):
            path_unique.append(trans2transUniqueMapping[path[ii]])

        ##-- figure plot
        plt.figure()
        n_states = B_map_unique.shape[0]
        n_frame  = B_map_unique.shape[1]
        y = np.arange(n_states+1)
        x = np.arange(n_frame) * hopsize_phoneticSimilarity / float(fs)

        plt.pcolormesh(x,y,B_map_unique)
        plt.plot(x,path_unique,'b',linewidth=3)
        plt.xlabel('time (s)')
        plt.ylabel('states')
        plt.yticks(y, transcription_unique, rotation='horizontal')
        plt.show()
项目:jingjuSingingPhraseMatching    作者:ronggong    | 项目源码 | 文件源码
def _pathPlot(self,transcription_gt,path_gt,path):
        '''
        plot ground truth path and decoded path
        :return:
        '''
        plt.figure()
        print self.B_map.shape
        y = np.arange(self.B_map.shape[0]+1)
        x = np.arange(self.B_map.shape[1]) * hopsize_phoneticSimilarity / float(fs)
        plt.pcolormesh(x,y,self.B_map)
        plt.plot(x,path,'b',linewidth=3)
        plt.plot(x,path_gt,'k',linewidth=3)
        plt.xlabel('time (s)')
        plt.ylabel('states')
        plt.show()
项目:OTC3D    作者:tiffanyts    | 项目源码 | 文件源码
def contour(self,title='',cbartitle = '',model=[], zmax = None, zmin = None, filename = None, resolution = 1, unit_str = '', bar = True):
        """ Returns a figure with contourplot of 2D spatial data. Insert filename to save the figure as an image. Increase resolution to increase detail of interpolated data (<1 to decrease)"""

        font = {'weight' : 'medium',
                'size'   : 22}

        xi = np.linspace(min(self.data.x), max(self.data.x),len(set(self.data.x))*resolution)
        yi = np.linspace(min(self.data.y), max(self.data.y),len(set(self.data.y))*resolution)


        zi = ml.griddata(self.data.x, self.data.y, self.data.v.interpolate(), xi, yi,interp='linear')

        fig = plt.figure()
        plt.rc('font', **font)
        plt.title(title)
        plt.contour(xi, yi, zi, 15, linewidths = 0, cmap=plt.cm.bone)
        plt.pcolormesh(xi, yi, zi, cmap = plt.get_cmap('rainbow'),vmax = zmax, vmin = zmin)
        if bar: cbar = plt.colorbar(); cbar.ax.set_ylabel(cbartitle)

        plt.absolute_import
        try:
            vertices = [(vertex.X(), vertex.Y()) for vertex in pyliburo.py3dmodel.fetch.vertex_list_2_point_list(pyliburo.py3dmodel.fetch.topos_frm_compound(model)["vertex"])]
            shape = patches.PathPatch(Path(vertices), facecolor='white', lw=0)
            plt.gca().add_patch(shape)
        except TypeError:
            pass
        plt.show()

        try:
            fig.savefig(filename)
        except TypeError:
            return fig

#    def plot_along_line(self,X,Y, tick_list):
#        V = self.data.v
#        plt.plot(heights, SVFs_can, label='Canyon')
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_by_max(state,norm=True,thresh=.001):
    fr = np.maximum(state,thresh)
    if norm:
#         fr = ((fr-np.mean(fr,axis=0))/np.std(fr,axis=0))
        fr = ((fr-np.min(fr,axis=0))/(1e-10+np.max(fr,axis=0)-np.min(fr,axis=0)))
    idx = np.argsort(np.argmax(fr,axis=0))
    plt.pcolormesh(fr[:,idx].T)
    plt.colorbar()
    plt.xlim([0,np.shape(fr)[0]])
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_input_output_angles(Win,W,Wout,brec):

    fig = plt.figure(figsize=(10,4))
    plt.subplot(2,3,1)
    plt.pcolormesh(gen_angle(Win,Win))
    plt.colorbar()
    plt.title('angle $W_{in}$ by $W_{in}$')
    plt.subplot(2,3,2)
    plt.pcolormesh(gen_angle(Wout.T,Wout.T))
    plt.colorbar()
    plt.title('angle $W_{out}$ by $W_{out}$')
    plt.subplot(2,3,3)
    plt.pcolormesh(gen_angle(Win,Wout.T))
    plt.colorbar()
    plt.title('angle $W_{in}$ by $W_{out}$')
    plt.subplot(2,3,4)
    plt.bar(range(3),calc_norm(Win))
    plt.xticks([])
    plt.xlim(-.2,3)
    plt.xlabel('Win')
    plt.ylabel('Norm')
    plt.subplot(2,3,5)
    plt.bar(range(2),calc_norm(Wout.T))
    plt.xticks([])
    plt.xlim(-.2,2)
    plt.xlabel('Wout')
    plt.ylabel('Norm')

    plt.tight_layout()

    return fig
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_biclustered_weights(W):
    import sklearn.cluster
    model = sklearn.cluster.bicluster.SpectralBiclustering(n_clusters=4, method='log', random_state=0)
    model.fit(W)

    fit_W = W[np.argsort(model.row_labels_)]
    fit_W = fit_W[:, np.argsort(model.column_labels_)]

    normW = calc_norm(fit_W)
    angle_W = np.arccos(np.clip((W.T.dot(W))/np.outer(normW,normW),-1.,1.))

    min_val = np.min(angle_W)
    max_val = np.max(angle_W)
    xx = np.linspace(min_val,max_val,50)
    histW, bin_edgesW = np.histogram(angle_W[np.tril(np.ones_like(W),-1)>0],xx)

    fig = plt.figure(figsize=(10,4))

    plt.subplot(1,2,1)
    plt.pcolormesh(fit_W,cmap='viridis')
    plt.colorbar()
    #plt.axes().set_aspect('equal')
    plt.title('Biclustering of Wrec')

    plt.subplot(1,2,2)
    plt.pcolormesh(angle_W)
    plt.colorbar()
    plt.title('$\measuredangle$ W clustered')

    return fig
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_principal_angles(W,s,data):
    masks = s[:,0,:].T>0
    max_ev = np.zeros(data[0].shape[1])

    pos = []
    neg = []
    leading = []
    for ii in range(data[0].shape[1]):
        evals,evecs = np.linalg.eig(W*masks[:,ii]-np.eye(100))
        max_ev[ii] = np.max(evals.real)
        pos.append(evecs[:,evals>0])
        neg.append(evecs[:,evals<0])
        leading.append(evecs[:,np.argsort(np.abs(evals.real))[:10]]) #.reshape([100,2]))


    xx = np.arange(0,data[0].shape[1],1)
    pa = np.zeros([len(xx),len(xx)])

    basis = leading

    for ii,pre in enumerate(xx):
        for jj,post in enumerate(xx):
            if basis[pre].shape[1]*basis[post].shape[1]>0:
                pas = principal_angle(basis[pre],basis[post])
                pa[ii,jj] = np.nanmean(pas)
            else:
                pa[ii,jj] = 0.

    fig = plt.figure()        
    plt.pcolormesh(pa,vmin=0,vmax=90)
    plt.colorbar()
    plt.ylim([0,pa.shape[0]])
    plt.xlim([0,pa.shape[1]])

    plt.axes().set_aspect('equal')
    plt.title('Principal Angle Analysis')
    plt.xlabel('Time')
    plt.ylabel('Time')

    return fig
项目:SwarmPackagePy    作者:SISDevelop    | 项目源码 | 文件源码
def animation(agents, function, lb, ub, sr=False):

    side = np.linspace(lb, ub, (ub - lb) * 5)
    X, Y = np.meshgrid(side, side)
    Z = np.array([np.array([function([X[i][j], Y[i][j]])
                            for j in range(len(X))])
                  for i in range(len(X[0]))])

    fig = plt.figure()
    plt.axes(xlim=(lb, ub), ylim=(lb, ub))
    plt.pcolormesh(X, Y, Z, shading='gouraud')
    plt.colorbar()

    x = np.array([j[0] for j in agents[0]])
    y = np.array([j[1] for j in agents[0]])
    sc = plt.scatter(x, y, color='black')

    plt.title(function.__name__, loc='left')

    def an(i):
        x = np.array([j[0] for j in agents[i]])
        y = np.array([j[1] for j in agents[i]])
        sc.set_offsets(list(zip(x, y)))
        plt.title('iteration: {}'.format(i), loc='right')

    ani = matplotlib.animation.FuncAnimation(fig, an, frames=len(agents) - 1)

    if sr:

        ani.save('result.mp4')

    plt.show()
项目:prml    作者:Yevgnen    | 项目源码 | 文件源码
def main():
    N = 500
    K = 5
    mean = np.array([[5, 0], [0, 5], [-5, 0], [0, -5], [0, 0]])
    cov = np.array([[1, -1], [1, 1]])
    sample = ClassificationSample(N, K, mean, cov)
    X = sample.X
    T = sample.T

    M = 2
    classifier = SoftmaxRegression(X, T, M, K)
    classifier.train(tol=1e-5, max_iter=int(1e3), lr=1e-1, eta=0.95)

    x_min, y_min = X[:, 0].min() - 1, X[:, 1].min() - 1
    x_max, y_max = X[:, 0].max() + 1, X[:, 1].max() + 1

    plt.figure()
    color = np.array(['r', 'g', 'b', 'c', 'y'])
    cmap = ListedColormap(['#FFAAAA', '#AAFFAA', '#3380e6', '#00dcdc', '#fbf896'])

    h = 0.05
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    mesh = np.c_[xx.ravel(), yy.ravel()]
    pred = classifier.predict(mesh).argmax(axis=1)
    pred = pred.reshape(xx.shape)
    plt.pcolormesh(xx, yy, pred, cmap=cmap)

    for n in range(N):
        plt.scatter(X[n, 0], X[n, 1], c=color[np.argmax(T[n, :])])

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.show()
项目:prml    作者:Yevgnen    | 项目源码 | 文件源码
def main():
    N = 4000
    n_features = 2
    n_classes = 4
    K = n_classes
    mean = np.array([[5, 0], [0, 5], [-5, 8], [0, 0]])
    cov = np.array([[2, -1], [1, 1]])
    sample = ClassificationSample(N, K, mean, cov)
    X = sample.X
    T = sample.T
    classifier = SoftmaxRegression(n_features, n_classes)
    classifier.fit(X, T)

    x_min, y_min = X[0, :].min() - 1, X[1, :].min() - 1
    x_max, y_max = X[0, :].max() + 1, X[1, :].max() + 1
    color = np.array(['r', 'g', 'b', 'y'])
    cmap = ListedColormap(['#FFAAAA', '#AAFFAA', '#3380e6', '#fbf896'])

    plt.figure()
    h = 0.05
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    mesh = np.c_[xx.ravel(), yy.ravel()]
    predictions = classifier.predict(mesh.T)
    predictions = predictions.reshape(xx.shape)
    plt.pcolormesh(xx, yy, predictions, cmap=cmap)
    plt.scatter(X[0, :], X[1, :], marker='x', c=color[T])
    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.show()
项目:Artificial-Intelligence-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def visualize_classifier(classifier, X, y):
    # Define the minimum and maximum values for X and Y
    # that will be used in the mesh grid
    min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
    min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0

    # Define the step size to use in plotting the mesh grid 
    mesh_step_size = 0.01

    # Define the mesh grid of X and Y values
    x_vals, y_vals = np.meshgrid(np.arange(min_x, max_x, mesh_step_size), np.arange(min_y, max_y, mesh_step_size))

    # Run the classifier on the mesh grid
    output = classifier.predict(np.c_[x_vals.ravel(), y_vals.ravel()])

    # Reshape the output array
    output = output.reshape(x_vals.shape)

    # Create a plot
    plt.figure()

    # Choose a color scheme for the plot 
    plt.pcolormesh(x_vals, y_vals, output, cmap=plt.cm.gray)

    # Overlay the training points on the plot 
    plt.scatter(X[:, 0], X[:, 1], c=y, s=75, edgecolors='black', linewidth=1, cmap=plt.cm.Paired)

    # Specify the boundaries of the plot
    plt.xlim(x_vals.min(), x_vals.max())
    plt.ylim(y_vals.min(), y_vals.max())

    # Specify the ticks on the X and Y axes
    plt.xticks((np.arange(int(X[:, 0].min() - 1), int(X[:, 0].max() + 1), 1.0)))
    plt.yticks((np.arange(int(X[:, 1].min() - 1), int(X[:, 1].max() + 1), 1.0)))

    plt.show()
项目:Artificial-Intelligence-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def visualize_classifier(classifier, X, y, title=''):
    # Define the minimum and maximum values for X and Y
    # that will be used in the mesh grid
    min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
    min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0

    # Define the step size to use in plotting the mesh grid 
    mesh_step_size = 0.01

    # Define the mesh grid of X and Y values
    x_vals, y_vals = np.meshgrid(np.arange(min_x, max_x, mesh_step_size), np.arange(min_y, max_y, mesh_step_size))

    # Run the classifier on the mesh grid
    output = classifier.predict(np.c_[x_vals.ravel(), y_vals.ravel()])

    # Reshape the output array
    output = output.reshape(x_vals.shape)

    # Create a plot
    plt.figure()

    # Specify the title
    plt.title(title)

    # Choose a color scheme for the plot 
    plt.pcolormesh(x_vals, y_vals, output, cmap=plt.cm.gray)

    # Overlay the training points on the plot 
    plt.scatter(X[:, 0], X[:, 1], c=y, s=75, edgecolors='black', linewidth=1, cmap=plt.cm.Paired)

    # Specify the boundaries of the plot
    plt.xlim(x_vals.min(), x_vals.max())
    plt.ylim(y_vals.min(), y_vals.max())

    # Specify the ticks on the X and Y axes
    plt.xticks((np.arange(int(X[:, 0].min() - 1), int(X[:, 0].max() + 1), 1.0)))
    plt.yticks((np.arange(int(X[:, 1].min() - 1), int(X[:, 1].max() + 1), 1.0)))

    plt.show()
项目:RapidMoc    作者:cdr30    | 项目源码 | 文件源码
def main(configf, vfile, name):
    """ Plot meridional currents at RAPID section and region boundaries. """

    # Read config file
    config = ConfigParser.ConfigParser()
    config.read(configf)

    # Read boundaries of RAPID regions
    fc_minlon = config.getfloat('options', 'fc_minlon')
    fc_maxlon = config.getfloat('options', 'fc_maxlon')
    wbw_maxlon = config.getfloat('options', 'wbw_maxlon')

    # Load velocity data
    v = sections.ZonalSections(vfile, config, 'meridional_velocity')
    lons = v.x
    z_scaled = -np.sqrt(np.abs(v.z))

    if len(v.data.shape) == 3:
        vdat = v.data[0]
    else:
        vdat = v.data

    # Plot velocity data and overly boundaries
    fig = plt.figure(figsize=(10,6))
    zticks, zlabels = rapidplot.get_zscale_ticks()
    plt.pcolormesh(lons, z_scaled, vdat, vmin=vdat.min(), vmax=np.abs(vdat.min()),
                   cmap=plt.cm.RdBu_r)

    for lon in [fc_minlon, fc_maxlon, wbw_maxlon]:
        plt.plot([lon, lon], [z_scaled.min(), z_scaled.max()], '-k', linewidth=2)

    # Annotate figure
    plt.xlim([fc_minlon-2, wbw_maxlon+2])
    plt.xlabel('Longitude')
    plt.ylabel('Depth (m)')
    plt.yticks(zticks, zlabels)
    plt.title('Meridional velocity in %s\n Black lines indicate position of fc_minlon, fc_maxlon, wbw_maxlon' % 
              name)
    plt.colorbar()
    plt.show()
项目:machine-learning    作者:cinserra    | 项目源码 | 文件源码
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 1.0
    y_min = 0.0; y_max = 1.0

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    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)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="fast")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="slow")
    plt.legend()
    plt.xlabel("bumpiness")
    plt.ylabel("grade")

    plt.savefig("test.png")
项目:yellowbrick    作者:DistrictDataLabs    | 项目源码 | 文件源码
def show_plot(X, y, n_neighbors=10, h=0.2):
    # Create color maps
    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#AAAAFF'])
    cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000',])

    for weights in ['uniform', 'distance']:
        # we create an instance of Neighbours Classifier and fit the data.
        clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
        clf.fit(X, y)
        clf.n_neighbors = n_neighbors

        # Plot the decision boundary. For that, we will assign a color to each
        # point in the mesh [x_min, x_max]x[y_min, y_max].
        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)
        plt.figure()
        plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

        # Plot also the training points
        plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
        plt.xlim(xx.min(), xx.max())
        plt.ylim(yy.min(), yy.max())
        plt.title("3-Class classification (k = %i, weights = '%s')"
                  % (n_neighbors, weights))

    plt.show()
项目:iota    作者:amaneureka    | 项目源码 | 文件源码
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)
项目:ThinkX    作者:AllenDowney    | 项目源码 | 文件源码
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)
项目:randomforest-density-python    作者:ksanjeevan    | 项目源码 | 文件源码
def vizualize_both(self, fname='density_comp.png', show_data=False):
        X = self.grid[0]
        Y = self.grid[1]
        Z1 = self.P
        Z2 = self.Q

        fig = plt.figure(figsize=(12, 12))

        true_dist_params = (211, Z1, 'True Distribution', cm.Greens)
        rf_dist_params = (212, Z2, 'Density Forest Estimate; JSD = %.3f'%(self.compute_JSD()), cm.Blues)

        for sp, Z, title, cmap in [true_dist_params, rf_dist_params]:
            ax = fig.add_subplot(sp)
            vmin=np.min(Z1)
            vmax=np.max(Z1)
            var = plt.pcolormesh(np.array(X),np.array(Y),np.array(Z), cmap=cmap, vmin=vmin, vmax=vmax)
            plt.colorbar(var, ticks=np.arange(vmin, vmax, (vmax-vmin)/8))
            ax = plt.gca()
            gris = 200.0
            ax.set_facecolor((gris/255, gris/255, gris/255))

            if show_data:
                ax.scatter(*zip(*self.data), alpha=.5, c='k', s=10., lw=0)

            ax.set_title(title)
            plt.xlim(np.min(X), np.max(X))
            plt.ylim(np.min(Y), np.max(Y))
            plt.grid()


        fig.savefig(fname, format='png')
        plt.close()
项目:randomforest-density-python    作者:ksanjeevan    | 项目源码 | 文件源码
def plot_density(self, fname='density_estimation.png'):

        X = self.grid[0]
        Y = self.grid[1]
        Z = self.dist

        fig = plt.figure(figsize=(12, 12))
        ax = fig.add_subplot(111)


        vmin=np.min(Z)
        vmax=np.max(Z)
        var = plt.pcolormesh(np.array(X),np.array(Y),np.array(Z), cmap=cm.Blues, vmin=vmin, vmax=vmax)
        plt.colorbar(var, ticks=np.arange(vmin, vmax, (vmax-vmin)/8))

        ax = plt.gca()

        gris = 200.0
        ax.set_facecolor((gris/255, gris/255, gris/255))

        ax.scatter(*zip(*self.data), alpha=.5, c='k', s=10., lw=0)

        plt.xlim(np.min(X), np.max(X))
        plt.ylim(np.min(Y), np.max(Y))
        plt.grid()

        ax.set_title('rho = %s, |T| = %d, max_entropy = %.2f'%(self.rho, self.f_size, self.opt_entropy))

        fig.savefig(fname, format='png')
        plt.close()
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def plot_confusion_matrix(experiment_path):
    config_parser = configparser.ConfigParser()
    config_parser.read(os.path.join(experiment_path, "conf.ini"))
    model_name = config_parser['MODEL']['ModelName']
    y_trues, y_scores = load_predictions(experiment_path)

    y_true = [np.argmax(y_t) for y_t in y_trues]
    y_pred = [np.argmax(y_s) for y_s in y_scores]

    confusion_matrix = metrics.confusion_matrix(y_true, y_pred)
    # confusion_matrix = np.flip(confusion_matrix, 0)

    title = "Confusion Matrix ({})".format(model_name)

    cmap = plt.cm.get_cmap('jet')
    fig = plt.figure()
    plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    plt.ylabel("True class")
    plt.xlabel("Predicted class")
    # plt.pcolormesh(confusion_matrix, cmap=cmap)
    fig.savefig(os.path.join(experiment_path, "confusion.png"))

    fig.clf()
    plt.close(fig)

    (nb_rows, nb_cols) = confusion_matrix.shape

    confusions = []
    for i in range(nb_rows):
        confused_predictions = np.sum(confusion_matrix[:,i]) - confusion_matrix[i][i]
        confusions.append((i, confused_predictions))

    sorted_confusions = sorted(confusions, key=lambda x: x[1], reverse=True)
    for (i, confusion) in sorted_confusions:
        print("Class {}: {}".format(i, confusion))
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def plot_confusion_matrix(picke_file, directory):
    with open(picke_file, 'rb') as input:
        stats = pickle.load(input)

    index_to_species = loader.build_class_index(directory)
    species_to_index = {v: k for k, v in index_to_species.items()}

    size = len(index_to_species.keys())
    confusion_matrix = np.zeros((size, size))
    for index, species in index_to_species.items():
        row = np.zeros(size)
        stat = stats[species]
        confusion = stat['confusion']
        for species, value in confusion.items():
            i = species_to_index[species]
            row[i] = value
        if np.sum(row) <= 0:
            print(species)
        confusion_matrix[index,:] = row

    for i in range(size):
        species = index_to_species[i]
        print(species, "(" + str(i) + ")", np.sum(confusion_matrix[:,i]))

    print("Total predictions:", np.sum(confusion_matrix))
    confusion_matrix = np.flip(confusion_matrix, 0)
    for i in range(size):
        if np.sum(confusion_matrix[i]) <= 0:
            print("Something is wrong")
        confusion_matrix[i] = confusion_matrix[i]/np.sum(confusion_matrix[i])


    cmap = plt.cm.get_cmap('jet')
    fig = plt.figure()
    # plt.gca().invert_yaxis()
    plt.pcolormesh(confusion_matrix, cmap=cmap)
    fig.savefig("confusion.png")

    fig.clf()
    plt.close(fig)
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def signal_and_noise_spectrogram_from_wave_file(filepath):

    (fs, wave) = utils.read_wave_file(filepath)
    spectrogram = sp.wave_to_sample_spectrogram(wave, fs)
    signal_wave, noise_wave = pp.preprocess_wave(wave, fs)
    spectrogram_signal = sp.wave_to_sample_spectrogram(signal_wave, fs)
    spectrogram_noise = sp.wave_to_sample_spectrogram(noise_wave, fs)

    fig = plt.figure(1)
    cmap = plt.cm.get_cmap('jet')
    gs = gridspec.GridSpec(2, 2)
    # whole spectrogram
    ax1 = fig.add_subplot(gs[0,:])
    ax1.pcolormesh(spectrogram, cmap=cmap)
    ax1.set_title("Sound")

    ax2 = fig.add_subplot(gs[1,0])
    ax2.pcolormesh(spectrogram_signal, cmap=cmap)
    ax2.set_title("Signal")

    ax3 = fig.add_subplot(gs[1,1])
    ax3.pcolormesh(spectrogram_noise, cmap=cmap)
    ax3.set_title("Noise")

    gs.update(wspace=0.5, hspace=0.5)

    basename = utils.get_basename_without_ext(filepath)
    fig.savefig(basename+"_noise_signal.png")

    fig.clf()
    plt.close(fig)
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def same_class_augmentation_from_dir(class_dir):
    sig_paths = glob.glob(os.path.join(class_dir, "*.wav"))
    sig_path = np.random.choice(sig_paths, 1, replace=False)[0]
    (fs, sig) = utils.read_wave_file(sig_path)

    aug_sig_path = np.random.choice(sig_paths, 1, replace=False)[0]
    (fs, aug_sig) = utils.read_wave_file(aug_sig_path)
    alpha = np.random.rand()
    combined_sig = (1.0-alpha)*sig + alpha*aug_sig

    spectrogram_sig = sp.wave_to_sample_spectrogram(sig, fs)
    spectrogram_aug_sig = sp.wave_to_sample_spectrogram(aug_sig, fs)
    spectrogram_combined_sig = sp.wave_to_sample_spectrogram(combined_sig, fs)

    fig = plt.figure(1)
    cmap = plt.cm.get_cmap('jet')
    gs = gridspec.GridSpec(3, 1)
    # whole spectrogram
    ax1 = fig.add_subplot(gs[0,0])
    ax1.pcolormesh(spectrogram_sig, cmap=cmap)
    ax1.set_title("Signal 1")

    ax2 = fig.add_subplot(gs[1,0])
    ax2.pcolormesh(spectrogram_aug_sig, cmap=cmap)
    ax2.set_title("Signal 2")

    ax3 = fig.add_subplot(gs[2,0])
    ax3.pcolormesh(spectrogram_combined_sig, cmap=cmap)
    ax3.set_title("Augmented Signal (alpha=" + str(alpha) + ")")

    gs.update(wspace=0.5, hspace=0.5)

    basename = utils.get_basename_without_ext(sig_path)
    fig.savefig(basename+"_same_class_augmentation.png")

    fig.clf()
    plt.close(fig)
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def save_matrix_to_file(Sxx, title, filename):
    cmap = plt.cm.get_cmap('jet')
    #cmap = grayify_cmap('cubehelix_r')
    fig = plt.figure()
    fig.suptitle(title, fontsize=12)
    plt.pcolormesh(Sxx, cmap=cmap)
    plt.ylabel('Frequency Bins')
    plt.xlabel('Window Samples')
    fig.savefig(filename)
    # close
    plt.clf()
    plt.close()
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def subplot_image(Sxx, n_subplot, title):
    cmap = grayify_cmap('cubehelix_r')
    # cmap = plt.cm.get_cmap('jet')
    # cmap = grayify_cmap('jet')
    plt.subplot(n_subplot)
    plt.title(title)
    plt.pcolormesh(Sxx, cmap=cmap)
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def plot_matrix(Sxx, title):
    # cmap = grayify_cmap('cubehelix_r')
    cmap = plt.cm.get_cmap('jet')
    fig = plt.figure()
    fig.suptitle(title, fontsize=12)
    plt.pcolormesh(Sxx, cmap=cmap)
    plt.ylabel('Frequency Bins')
    plt.xlabel('Window Samples')
    plt.show()
项目:pymchelper    作者:DataMedSci    | 项目源码 | 文件源码
def _save_2d_error_plot(self, detector, xlist, ylist, elist, x_axis_label, y_axis_label, z_axis_label):
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        from matplotlib import colors

        # configure logscale on X and Y axis (both for positive and negative numbers)

        fig, ax = plt.subplots(1, 1)

        if PlotAxis.x in self.axis_with_logscale:
            plt.xscale('symlog')
        if PlotAxis.y in self.axis_with_logscale:
            plt.yscale('symlog')

        if PlotAxis.z in self.axis_with_logscale:
            norm = colors.LogNorm(vmin=elist[elist > 0].min(), vmax=elist.max())
        else:
            norm = colors.Normalize(vmin=elist.min(), vmax=elist.max())

        plt.xlabel(x_axis_label)
        plt.ylabel(y_axis_label)

        mesh = plt.pcolormesh(xlist, ylist, elist.clip(0.0), cmap=self.colormap, norm=norm)
        cbar = fig.colorbar(mesh)
        cbar.set_label(label=z_axis_label, rotation=270, verticalalignment='bottom')

        base_name, _ = os.path.splitext(self.plot_filename)
        plt.savefig(base_name + "_error.png")
        plt.close()
项目:mcmc_line_fitting    作者:jakeown    | 项目源码 | 文件源码
def mcmc_plot(param_file):
    params = numpy.loadtxt(param_file, delimiter=',', unpack=True) # params = [T_pk, sig, tau, v_in, v_lsr]
    params_names = ['T_pk', 'sig', 'tau', 'v_in', 'v_lsr']
    plot_names = ['T$_{pk}$', '$\sigma$', r'$\tau$', 'v$_{in}$', 'v$_{lsr}$']
    counter=0
    nbins = 40
    for i in params_names: 
        #Plot 1D Histograms
        fig1 = plt.figure()
        plt.hist(params[counter], bins=40, label='40 bins', range = [min(params[counter]), max(params[counter])],           facecolor='g')
        plt.legend(loc='upper left')
        plt.title(plot_names[counter]+' histogram')
        plt.ylabel('counts')
        plt.xlabel(plot_names[counter])
        #plt.show()
        pylab.savefig(i +'_hist.pdf')
        plt.close()

        #Plot iterations vs parameter plot
        fig1 = plt.figure()
        plt.scatter(numpy.array(range(len(params[counter])))+1, params[counter])
        plt.title(plot_names[counter] + ' - ' + str(len(params[counter])) +' iterations')
        plt.ylabel(plot_names[counter])
        plt.xlabel('iteration')
        #plt.show()
        pylab.savefig(i +'_iterations.pdf')
        plt.close()

        # Create the 2D histograms
        nrange = [[min(params[3]), max(params[3])],[min(params[counter]), max(params[counter])]]
        H, xedges, yedges = numpy.histogram2d(params[3],params[counter],bins=nbins,range = nrange)
        H = numpy.rot90(H)
        H = numpy.flipud(H)
        # Plot 2D histogram using pcolor
        fig4 = plt.figure()
        plt.pcolormesh(xedges,yedges,H)
        plt.xlabel('v$_{in}$')
        plt.ylabel(plot_names[counter])
        plt.title(plot_names[counter]+' vs v$_{in}$ - ' + str(len(params[3])) + ' iterations')
        plt.xlim(min(xedges), max(xedges))
        plt.ylim(min(yedges), max(yedges))
        cbar = plt.colorbar()
        cbar.ax.set_ylabel('Counts')
        #plt.show()
        pylab.savefig(i +'_v_in_2dhist.pdf')
        plt.close()
        counter += 1
项目:digital_rf    作者:MITHaystack    | 项目源码 | 文件源码
def plot_resid(d,savename='resfig1.png'):
    """
        Plots the residual frequency after the first wipe using the TLE velocity.
    """
    flim = [-2.e3, 2.e3]
    t = d['tvec']

    dates = [dt.datetime.fromtimestamp(ts) for ts in t]
    datenums = md.date2num(dates)
    xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')

    fig1 = plt.figure(figsize=(7, 9))
    doppler_residual = sp.interpolate.interp1d(d['tvec'],d['dopfit'])
    fvec = d["fvec"]
    res0 = d["res0"]
    res1 = d["res1"]
    plt.subplot(211)
    mesh = plt.pcolormesh(datenums, fvec, sp.transpose(10.*sp.log10(res0+1e-12)), vmin=-5, vmax=25)
    plt.plot(datenums, (150.0/400.0)*doppler_residual(t), "r--", label="doppler resid")
    ax = plt.gca()
    ax.xaxis.set_major_formatter(xfmt)
    plt.ylim(flim)
    plt.subplots_adjust(bottom=0.2)
    plt.xticks(rotation=25)
    plt.xlabel("UTC")
    plt.ylabel("Frequency (Hz)")
    plt.title("Power ch0 (dB) %1.2f MHz"%(150.012))
    plt.legend()
    plt.colorbar(mesh, ax=ax)

     # quicklook spectra of residuals spectra along with measured Doppler residual from second channel.
    plt.subplot(212)
    mesh = plt.pcolormesh(datenums, fvec, sp.transpose(10.*sp.log10(res1+1e-12)), vmin=-5, vmax=25)
    plt.plot(datenums, doppler_residual(t), "r--", label="doppler resid")
    ax = plt.gca()
    ax.xaxis.set_major_formatter(xfmt)
    plt.ylim(flim)
    plt.xlabel("UTC")
    plt.ylabel("Frequency (Hz)")
    plt.title("Power ch1 (dB), %1.2f MHz"%(400.032))
    plt.subplots_adjust(bottom=0.2)
    plt.xticks(rotation=25)
    plt.legend()
    plt.colorbar(mesh, ax=ax)

    plt.tight_layout()
    print('Saving residual plots: '+savename)
    plt.savefig(savename, dpi=300)
    plt.close(fig1)
项目:Python-Machine-Learning-Cookbook    作者:PacktPublishing    | 项目源码 | 文件源码
def plot_classifier(classifier, X, y, title='Classifier boundaries', annotate=False):
    # define ranges to plot the figure 
    x_min, x_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0
    y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 1]) + 1.0

    # denotes the step size that will be used in the mesh grid
    step_size = 0.01

    # define the mesh grid
    x_values, y_values = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))

    # compute the classifier output
    mesh_output = classifier.predict(np.c_[x_values.ravel(), y_values.ravel()])

    # reshape the array
    mesh_output = mesh_output.reshape(x_values.shape)

    # Plot the output using a colored plot 
    plt.figure()

    # Set the title
    plt.title(title)

    # choose a color scheme you can find all the options 
    # here: http://matplotlib.org/examples/color/colormaps_reference.html
    plt.pcolormesh(x_values, y_values, mesh_output, cmap=plt.cm.Set1)

    # Overlay the training points on the plot 
    plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='black', linewidth=2, cmap=plt.cm.Set1)

    # specify the boundaries of the figure
    plt.xlim(x_values.min(), x_values.max())
    plt.ylim(y_values.min(), y_values.max())

    # specify the ticks on the X and Y axes
    plt.xticks(())
    plt.yticks(())

    if annotate:
        for x, y in zip(X[:, 0], X[:, 1]):
            # Full documentation of the function available here: 
            # http://matplotlib.org/api/text_api.html#matplotlib.text.Annotation
            plt.annotate(
                '(' + str(round(x, 1)) + ',' + str(round(y, 1)) + ')',
                xy = (x, y), xytext = (-15, 15), 
                textcoords = 'offset points', 
                horizontalalignment = 'right', 
                verticalalignment = 'bottom', 
                bbox = dict(boxstyle = 'round,pad=0.6', fc = 'white', alpha = 0.8),
                arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=0'))

# Print performance metrics
项目:Python-Machine-Learning-Cookbook    作者:PacktPublishing    | 项目源码 | 文件源码
def plot_classifier(classifier, X, y, title='Classifier boundaries', annotate=False):
    # define ranges to plot the figure 
    x_min, x_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0
    y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 1]) + 1.0

    # denotes the step size that will be used in the mesh grid
    step_size = 0.01

    # define the mesh grid
    x_values, y_values = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))

    # compute the classifier output
    mesh_output = classifier.predict(np.c_[x_values.ravel(), y_values.ravel()])

    # reshape the array
    mesh_output = mesh_output.reshape(x_values.shape)

    # Plot the output using a colored plot 
    plt.figure()

    # Set the title
    plt.title(title)

    # choose a color scheme you can find all the options 
    # here: http://matplotlib.org/examples/color/colormaps_reference.html
    plt.pcolormesh(x_values, y_values, mesh_output, cmap=plt.cm.gray)

    # Overlay the training points on the plot 
    plt.scatter(X[:, 0], X[:, 1], c=y, s=80, edgecolors='black', linewidth=1, cmap=plt.cm.Paired)

    # specify the boundaries of the figure
    plt.xlim(x_values.min(), x_values.max())
    plt.ylim(y_values.min(), y_values.max())

    # specify the ticks on the X and Y axes
    plt.xticks(())
    plt.yticks(())

    if annotate:
        for x, y in zip(X[:, 0], X[:, 1]):
            # Full documentation of the function available here: 
            # http://matplotlib.org/api/text_api.html#matplotlib.text.Annotation
            plt.annotate(
                '(' + str(round(x, 1)) + ',' + str(round(y, 1)) + ')',
                xy = (x, y), xytext = (-15, 15), 
                textcoords = 'offset points', 
                horizontalalignment = 'right', 
                verticalalignment = 'bottom', 
                bbox = dict(boxstyle = 'round,pad=0.6', fc = 'white', alpha = 0.8),
                arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=0'))

# Print performance metrics
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plot_map(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Plotting a map of the heating fraction of the unevolved stellar population for a face-on view of the galaxy ...")

        # Determine the path to the plot file
        path = fs.join(self.analysis_heating_path, "map.pdf")

        plt.figure()

        x = np.ma.MaskedArray(self.absorptions["X coordinate of cell center"], mask=self.mask).compressed()
        y = np.ma.MaskedArray(self.absorptions["Y coordinate of cell center"], mask=self.mask).compressed()
        z = self.heating_fractions_compressed

        #plt.pcolormesh(x, y, z, cmap='RdBu', vmin=0.0, vmax=1.0)

        from matplotlib import mlab

        x_ticks = x
        y_ticks = y

        z_grid = mlab.griddata(x, y, z, x, y)

        from matplotlib.backends import backend_agg as agg
        from matplotlib import cm

        # plot
        # fig = Figure()  # create the figure
        fig = plt.figure()
        agg.FigureCanvasAgg(fig)  # attach the rasterizer
        ax = fig.add_subplot(1, 1, 1)  # make axes to plot on
        ax.set_title("Interpolated Contour Plot of Experimental Data")
        ax.set_xlabel("X")
        ax.set_ylabel("Y")

        cmap = cm.get_cmap("hot")  # get the "hot" color map
        contourset = ax.contourf(x_ticks, y_ticks, z_grid, 10, cmap=cmap)

        plt.savefig(path)
        plt.close()

    # -----------------------------------------------------------------