Python matplotlib.pyplot.hold() Examples

The following are 30 code examples for showing how to use matplotlib.pyplot.hold(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .

Example 1
Project: radiometric_normalization   Author: planetlabs   File: display.py    License: Apache License 2.0 6 votes vote down vote up
def plot_histograms(file_name, candidate_data_multiple_bands,
                    reference_data_multiple_bands=None,
                    # Default is for Blue-Green-Red-NIR:
                    colour_order=['b', 'g', 'r', 'y'],
                    x_limits=None, y_limits=None):
    logging.info('Display: Creating histogram plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hold(True)
    for colour, c_band in zip(colour_order, candidate_data_multiple_bands):
        c_bh, c_bins = numpy.histogram(c_band, bins=256)
        plt.plot(c_bins[:-1], c_bh, color=colour, linestyle='-', linewidth=2)
    if reference_data_multiple_bands:
        for colour, r_band in zip(colour_order, reference_data_multiple_bands):
            r_bh, r_bins = numpy.histogram(r_band, bins=256)
            plt.plot(
                r_bins[:-1], r_bh, color=colour, linestyle='--', linewidth=2)
    plt.xlabel('DN')
    plt.ylabel('Number of pixels')
    if x_limits:
        plt.xlim(x_limits)
    if y_limits:
        plt.ylim(y_limits)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig) 
Example 2
Project: laplacian-meshes   Author: bmershon   File: Utilities2D.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getBarycentricCoords(A, B, C, X, checkValidity = True):
    T = np.array( [ [A.x - C.x, B.x - C.x ], [A.y - C.y, B.y - C.y] ] )
    y = np.array( [ [X.x - C.x], [X.y - C.y] ] )
    lambdas = linalg.solve(T, y)
    lambdas = lambdas.flatten()
    lambdas = np.append(lambdas, 1 - (lambdas[0] + lambdas[1]))
    if checkValidity:
        if (lambdas[0] < 0 or lambdas[1] < 0 or lambdas[2] < 0):
            print "ERROR: Not a convex combination; lambda = %s"%lambdas
            print "pointInsideConvexPolygon2D = %s"%pointInsideConvexPolygon2D([A, B, C], X, 0)
            plt.plot([A.x, B.x, C.x, A.x], [A.y, B.y, C.y, A.y], 'r')
            plt.hold(True)
            plt.plot([X.x], [X.y], 'b.')
            plt.show()
        assert (lambdas[0] >= 0 and lambdas[1] >= 0 and lambdas[2] >= 0)
    else:
        lambdas[0] = max(lambdas[0], 0)
        lambdas[1] = max(lambdas[1], 0)
        lambdas[2] = max(lambdas[2], 0)
    return lambdas 
Example 3
Project: parametric_modeling   Author: awesomebytes   File: lms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_traj(w, w_true, fname=None):
    """ Plot the trajectory of the filter coefficients

    Inputs:
        w: matrix of filter weights versus time
        w_true: vector of true filter weights 
        fname: what filename to export the figure to. If None, then doesn't
        export

    """
    plt.figure()
    n = np.arange(w.shape[0])
    n_ones = np.ones(w.shape[0])
    plt.hold(True)
    # NOTE: This construction places a limit of 4 on the filter order
    plt_colors = ['b', 'r', 'g', 'k']
    for p in xrange(w.shape[1]):
        plt.plot(n, w[:,p], '{}-'.format(plt_colors[p]), label='w({})'.format(p))
        plt.plot(n, w_true[p] * n_ones, '{}--'.format(plt_colors[p]))
    plt.xlabel('Iteration')
    plt.ylabel('Coefficients')
    plt.legend()
    if fname:
        plt.savefig(fname)
        plt.close() 
Example 4
Project: geoio   Author: DigitalGlobe   File: plotting.py    License: MIT License 6 votes vote down vote up
def hist(data):
    """Convenience method to do all the plotting gymnastics to get a resonable
    looking histogram plot.

    Input: data - numpy array in gdal format - (bands, x, y)

    Returns:  matplotlib figure handle

    Adapted from:
    http://nbviewer.jupyter.org/github/HyperionAnalytics/PyDataNYC2014/blob/master/color_image_processing.ipynb
    """

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    plt.hold(True)
    for x in xrange(len(data[:,0,0])):
        counts, edges = np.histogram(data[x,:,:],bins=100)
        centers = [(edges[i]+edges[i+1])/2.0 for i,v in enumerate(edges[:-1])]
        ax1.plot(centers,counts)
    plt.hold(False)

    plt.show(block=False)

    # return fig 
Example 5
Project: python_primer   Author: noahwaterfieldprice   File: animate_Taylor_series.py    License: MIT License 6 votes vote down vote up
def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact, exactname):
    x = np.linspace(xmin, xmax, n)
    s = np.zeros(len(x))
    counter = 1
    for k in range(M, N + 1):
        s += fk(x, k)
        plt.plot(x, s, linewidth=2, color='#67001f')
        plt.hold(1)
        plt.plot(x, exact(x), '--', linewidth=2, color='#053061')
        plt.hold(0)
        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)
        plt.legend(['Taylor series approximation - %d terms' %
                   counter, exactname])
        plt.savefig('tmp_%04d.png' % counter)
        counter += 1 
Example 6
Project: python_primer   Author: noahwaterfieldprice   File: planet_orbit.py    License: MIT License 6 votes vote down vote up
def animate_orbit(a, b, omega, n):
    tlist = np.linspace(0, 2 * np.pi / omega, n)
    xorbit, yorbit = orbit_path(tlist, a, b, omega)
    counter = 0
    for t in tlist:
        x, y = orbit_path(t, a, b, omega)
        plt.plot(xorbit, yorbit, '--', color='#67001f', linewidth=2)
        plt.hold(1)
        plt.plot(x, y, 'ro', markerfacecolor='#2166ac',
                 markeredgecolor='#053061', markeredgewidth=2, markersize=20)
        plt.hold(0)
        plt.xlim([xorbit.min() * 1.1, xorbit.max() * 1.1])
        plt.ylim([yorbit.min() * 1.1, yorbit.max() * 1.1])
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Instantaneous velocity = %4f' % inst_vel(t, a, b, omega))
        plt.savefig('tmp_%03d.png' % counter)
        counter += 1 
Example 7
Project: python_primer   Author: noahwaterfieldprice   File: sinesum1_movie.py    License: MIT License 6 votes vote down vote up
def animate_series(fk, N, tmax, n, exact, exactname):
    t = np.linspace(0, tmax, n)
    s = np.zeros(len(t))
    counter = 1
    for k in range(0, N + 1):
        s = S(t, k, tmax)
        plt.plot(t, s, linewidth=2, color='#67001f')
        plt.hold(1)
        plt.plot(t, exact(t, tmax), '--', linewidth=2, color='#053061')
        plt.hold(0)
        plt.xlim(0, tmax)
        plt.ylim(-1.3, 1.3)
        plt.legend(['Sine sum - %d terms' %
                   counter, exactname])
        plt.savefig('tmp_%04d.png' % counter)
        counter += 1 
Example 8
Project: SynthText   Author: ankush-me   File: synthgen.py    License: Apache License 2.0 6 votes vote down vote up
def viz_textbb(fignum,text_im, bb_list,alpha=1.0):
    """
    text_im : image containing text
    bb_list : list of 2x4xn_i boundinb-box matrices
    """
    plt.close(fignum)
    plt.figure(fignum)
    plt.imshow(text_im)
    plt.hold(True)
    H,W = text_im.shape[:2]
    for i in xrange(len(bb_list)):
        bbs = bb_list[i]
        ni = bbs.shape[-1]
        for j in xrange(ni):
            bb = bbs[:,:,j]
            bb = np.c_[bb,bb[:,0]]
            plt.plot(bb[0,:], bb[1,:], 'r', linewidth=2, alpha=alpha)
    plt.gca().set_xlim([0,W-1])
    plt.gca().set_ylim([H-1,0])
    plt.show(block=False) 
Example 9
Project: ConvNetQuake   Author: tperol   File: fig_comparison.py    License: MIT License 6 votes vote down vote up
def fig_memory_usage():

    # FAST memory
    x = [1,3,7,14,30,90,180]
    y_fast = [0.653,1.44,2.94,4.97,9.05,19.9,35.2]
    # ConvNetQuake
    y_convnet = [6.8*1e-5]*7
    # Create figure
    plt.loglog(x,y_fast,"o-")
    plt.hold('on')
    plt.loglog(x,y_convnet,"o-")
    # plot markers
    plt.loglog(x,[1e-5,1e-5,1e-5,1e-5,1e-5,1e-5,1e-5],'o')
    plt.ylabel("Memory usage (GB)")
    plt.xlabel("Continous data duration (days)")
    plt.xlim(1,180)
    plt.grid("on")
    plt.savefig("./figures/memoryusage.eps")
    plt.close() 
Example 10
Project: ConvNetQuake   Author: tperol   File: fig_comparison.py    License: MIT License 6 votes vote down vote up
def fig_run_time():
    # fast run time
    x_fast = [1,3,7,14,30,90,180]
    y_fast = [289,1.13*1e3,2.48*1e3,5.41*1e3,1.56*1e4,
              6.61*1e4,1.98*1e5]
    x_auto = [1,3]
    y_auto = [1.54*1e4, 8.06*1e5]
    x_convnet = [1,3,7,14,30]
    y_convnet = [9,27,61,144,291]
    # create figure
    plt.loglog(x_auto,y_auto,"o-")
    plt.hold('on')
    plt.loglog(x_fast[0:5],y_fast[0:5],"o-")
    plt.loglog(x_convnet,y_convnet,"o-")
    # plot x markers
    plt.loglog(x_convnet,[1e0]*len(x_convnet),'o')
    # plot y markers
    y_markers = [1,60,3600,3600*24]
    plt.plot([1]*4,y_markers,'ko')
    plt.ylabel("run time (s)")
    plt.xlabel("continous data duration (days)")
    plt.xlim(1,35)
    plt.grid("on")
    plt.savefig("./figures/runtimes.eps") 
Example 11
Project: director   Author: RobotLocomotion   File: terrain.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def drawSamples(self, nsamples):
        import matplotlib.pyplot as plt
        plt.figure(1)
        plt.clf()
        plt.hold(True)
        k = ConvexHull(self.bot_pts.T).vertices
        k = np.hstack((k, k[0]))
        n = self.planar_polyhedron.generators.shape[0]
        plt.plot(self.planar_polyhedron.generators.T[0,list(range(n)) + [0]],
                 self.planar_polyhedron.generators.T[1,list(range(n)) + [0]], 'r.-')
        samples = sample_convex_polytope(self.c_space_polyhedron.A,
                                         self.c_space_polyhedron.b,
                                         500)
        for i in range(samples.shape[1]):
            R = np.array([[np.cos(samples[2,i]), -np.sin(samples[2,i])],
                          [np.sin(samples[2,i]), np.cos(samples[2,i])]])
            V = R.dot(self.bot_pts[:,k])
            V = V + samples[:2, i].reshape((2,1))
            plt.plot(V[0,:], V[1,:], 'k-')
        plt.show() 
Example 12
Project: emailinsight   Author: andreykurenkov   File: kerasExperiments.py    License: MIT License 6 votes vote down vote up
def make_plots(xs,ys,labels,title=None,x_name=None,y_name=None,y_bounds=None,save_to=None):
    colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
    handles = []
    plt.figure()
    plt.hold(True)
    for i in range(len(labels)):
        plot, = make_plot(xs[i],ys[i],color=colors[i%len(colors)],new_fig=False)
        handles.append(plot)
    plt.legend(handles,labels)
    if title is not None:
        plt.title(title)
    if x_name is not None:
        plt.xlabel(x_name)
    if y_name is not None:
        plt.ylabel(y_name)
    if y_bounds is not None:
        plt.ylim(y_bounds)
    if save_to is not None:
        plt.savefig(save_to,bbox_inches='tight')
    plt.hold(False) 
Example 13
Project: PReMVOS   Author: JonathonLuiten   File: plot_learn_curve2.py    License: MIT License 6 votes vote down vote up
def doit(fn, col1, col2, tag):
  train = []
  val = []
  with open(fn) as f:
    for l in f:
      if "finished" in l:
        sp = l.split()
        #clip to 5
        # tr = min(float(sp[col1]), 5.0)
        # va = min(float(sp[col2]), 5.0)
        tr = float(sp[col1])
        va = float(sp[col2])
        # if tr>1: tr = 1/tr
        # if va>1: va = 1/va

        train.append(tr)
        val.append(va)
  plt.plot(train, label="train")
  plt.hold(True)
  plt.plot(val, label="val")
  plt.legend()
  plt.title(fn + " " + tag)
  #plt.show() 
Example 14
Project: MinutiaeNet   Author: luannd   File: MinutiaeNet_utils.py    License: MIT License 6 votes vote down vote up
def draw_minutiae(image, minutiae, fname, saveimage= False, r=15, drawScore=False):
    image = np.squeeze(image)
    fig = plt.figure()
    

    plt.imshow(image,cmap='gray')
    plt.hold(True)
    # Check if no minutiae
    if minutiae.shape[0] > 0:
        plt.plot(minutiae[:, 0], minutiae[:, 1], 'rs', fillstyle='none', linewidth=1)
        for x, y, o, s in minutiae:
            plt.plot([x, x+r*np.cos(o)], [y, y+r*np.sin(o)], 'r-')
            if drawScore == True:
                plt.text(x - 10, y - 10, '%.2f' % s, color='yellow', fontsize=4)

    plt.axis([0,image.shape[1],image.shape[0],0])
    plt.axis('off')
    if saveimage:
        plt.savefig(fname, dpi=500, bbox_inches='tight', pad_inches = 0)
        plt.close(fig)
    else:
        plt.show()
    return 
Example 15
Project: rec-sys-experiments   Author: rnowling   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def plot_correlation(flname, title, x_label, y_label, dataset):
    """
    Scatter plot with line of best fit

    dataset - tuple of (x_values, y_values)
    """
    plt.clf()
    plt.hold(True)
    plt.scatter(dataset[0], dataset[1], alpha=0.7, color="k")
    xs = np.array(dataset[0])
    ys = np.array(dataset[1])
    A = np.vstack([xs, np.ones(len(xs))]).T
    m, c = np.linalg.lstsq(A, ys)[0]
    plt.plot(xs, m*xs + c, "c-")
    plt.xlabel(x_label, fontsize=16)
    plt.ylabel(y_label, fontsize=16)
    plt.xlim([0.25, max(dataset[0])])
    plt.ylim([10., max(dataset[1])])
    plt.title(title, fontsize=18)
    plt.savefig(flname, DPI=200) 
Example 16
Project: rec-sys-experiments   Author: rnowling   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def plot_histogram(flname, title, x_label, datasets):
    """
    Histogram

    dataset - list tuples of (frequencies, bins, style)
    """
    plt.clf()
    plt.hold(True)
    max_bin = 0
    for frequencies, bins, style in datasets:
        xs = []
        ys = []
        max_bin = max(max_bin, max(bins))
        for i, f in enumerate(frequencies):
            xs.append(bins[i])
            xs.append(bins[i+1])
            ys.append(f)
            ys.append(f)
        plt.plot(xs, ys, style)
    plt.xlabel(x_label, fontsize=16)
    plt.ylabel("Occurrences", fontsize=16)
    plt.xlim([0, max_bin + 1])
    plt.title(title, fontsize=18)
    plt.savefig(flname, DPI=200) 
Example 17
Project: spinalcordtoolbox   Author: neuropoly   File: sct_compute_hausdorff_distance.py    License: MIT License 5 votes vote down vote up
def show_results(self):
        import seaborn as sns
        import matplotlib.pyplot as plt
        import pandas as pd
        plt.hold(True)
        sns.set(style="whitegrid", palette="pastel", color_codes=True)
        plt.figure(figsize=(35, 20))

        data_dist = {"distances": [], "image": [], "slice": []}

        if self.dim_im == 2:
            data_dist["distances"].append([dist * self.dim_pix for dist in self.dist1_distribution])
            data_dist["image"].append(len(self.dist1_distribution) * [1])
            data_dist["slice"].append(len(self.dist1_distribution) * [0])

            data_dist["distances"].append([dist * self.dim_pix for dist in self.dist2_distribution])
            data_dist["image"].append(len(self.dist2_distribution) * [2])
            data_dist["slice"].append(len(self.dist2_distribution) * [0])

        if self.dim_im == 3:
            for i in range(len(self.distances)):
                data_dist["distances"].append([dist * self.dim_pix for dist in self.dist1_distribution[i]])
                data_dist["image"].append(len(self.dist1_distribution[i]) * [1])
                data_dist["slice"].append(len(self.dist1_distribution[i]) * [i])
                data_dist["distances"].append([dist * self.dim_pix for dist in self.dist2_distribution[i]])
                data_dist["image"].append(len(self.dist2_distribution[i]) * [2])
                data_dist["slice"].append(len(self.dist2_distribution[i]) * [i])

        for k in data_dist.keys():  # flatten the lists in data_dist
            data_dist[k] = [item for sublist in data_dist[k] for item in sublist]

        data_dist = pd.DataFrame(data_dist)
        sns.violinplot(x="slice", y="distances", hue="image", data=data_dist, split=True, inner="point", cut=0)
        plt.savefig('violin_plot.png')
        # plt.show()


# ---------------------------------------------------------------------------------------------------------------------- 
Example 18
Project: text_renderer   Author: Sanster   File: utils.py    License: MIT License 5 votes vote down vote up
def viz_img(text_im, fignum=1):
    """
    text_im : image containing text
    """
    text_im = text_im.astype(int)
    plt.close(fignum)
    plt.figure(fignum)
    plt.imshow(text_im, cmap='gray')
    plt.show(block=True)
    # plt.hold(True)
    #
    # H, W = text_im.shape[:2]
    # plt.gca().set_xlim([0, W - 1])
    # plt.gca().set_ylim([H - 1, 0])
    # plt.show(block=True) 
Example 19
Project: pyAudioAnalysis   Author: tyiannak   File: ShortTermFeatures.py    License: Apache License 2.0 5 votes vote down vote up
def chroma_features(signal, sampling_rate, num_fft):
    # TODO: 1 complexity
    # TODO: 2 bug with large windows

    num_chroma, num_freqs_per_chroma = \
        chroma_features_init(num_fft, sampling_rate)
    chroma_names = ['A', 'A#', 'B', 'C', 'C#', 'D',
                    'D#', 'E', 'F', 'F#', 'G', 'G#']
    spec = signal ** 2
    if num_chroma.max() < num_chroma.shape[0]:
        C = np.zeros((num_chroma.shape[0],))
        C[num_chroma] = spec
        C /= num_freqs_per_chroma[num_chroma]
    else:
        I = np.nonzero(num_chroma > num_chroma.shape[0])[0][0]
        C = np.zeros((num_chroma.shape[0],))
        C[num_chroma[0:I - 1]] = spec
        C /= num_freqs_per_chroma
    final_matrix = np.zeros((12, 1))
    newD = int(np.ceil(C.shape[0] / 12.0) * 12)
    C2 = np.zeros((newD,))
    C2[0:C.shape[0]] = C
    C2 = C2.reshape(int(C2.shape[0] / 12), 12)
    # for i in range(12):
    #    finalC[i] = np.sum(C[i:C.shape[0]:12])
    final_matrix = np.matrix(np.sum(C2, axis=0)).T
    final_matrix /= spec.sum()

    #    ax = plt.gca()
    #    plt.hold(False)
    #    plt.plot(finalC)
    #    ax.set_xticks(range(len(chromaNames)))
    #    ax.set_xticklabels(chromaNames)
    #    xaxis = np.arange(0, 0.02, 0.01);
    #    ax.set_yticks(range(len(xaxis)))
    #    ax.set_yticklabels(xaxis)
    #    plt.show(block=False)
    #    plt.draw()

    return chroma_names, final_matrix 
Example 20
Project: SynthText   Author: ankush-me   File: visualize_results.py    License: Apache License 2.0 5 votes vote down vote up
def viz_textbb(text_im, charBB_list, wordBB, alpha=1.0):
    """
    text_im : image containing text
    charBB_list : list of 2x4xn_i bounding-box matrices
    wordBB : 2x4xm matrix of word coordinates
    """
    plt.close(1)
    plt.figure(1)
    plt.imshow(text_im)
    plt.hold(True)
    H,W = text_im.shape[:2]

    # plot the character-BB:
    for i in xrange(len(charBB_list)):
        bbs = charBB_list[i]
        ni = bbs.shape[-1]
        for j in xrange(ni):
            bb = bbs[:,:,j]
            bb = np.c_[bb,bb[:,0]]
            plt.plot(bb[0,:], bb[1,:], 'r', alpha=alpha/2)

    # plot the word-BB:
    for i in xrange(wordBB.shape[-1]):
        bb = wordBB[:,:,i]
        bb = np.c_[bb,bb[:,0]]
        plt.plot(bb[0,:], bb[1,:], 'g', alpha=alpha)
        # visualize the indiv vertices:
        vcol = ['r','g','b','k']
        for j in xrange(4):
            plt.scatter(bb[0,j],bb[1,j],color=vcol[j])        

    plt.gca().set_xlim([0,W-1])
    plt.gca().set_ylim([H-1,0])
    plt.show(block=False) 
Example 21
Project: SMIT   Author: BCV-Uniandes   File: utils.py    License: MIT License 5 votes vote down vote up
def plot_txt(txt_file):
    import matplotlib.pyplot as plt
    lines = [line.strip().split() for line in open(txt_file).readlines()]
    legends = {idx: line
               for idx, line in enumerate(lines[0][1:])}  # 0 is epochs
    lines = lines[1:]
    epochs = []
    losses = {loss: [] for loss in legends.values()}
    for line in lines:
        epochs.append(line[0])
        for idx, loss in enumerate(line[1:]):
            losses[legends[idx]].append(float(loss))

    import pylab as pyl
    plot_file = txt_file.replace('.txt', '.pdf')
    _min = 4 if len(losses.keys()) > 9 else 3
    for idx, loss in enumerate(losses.keys()):
        # plot_file = txt_file.replace('.txt','_{}.jpg'.format(loss))

        plt.rcParams.update({'font.size': 10})
        ax1 = plt.subplot(3, _min, idx + 1)
        # err = plt.plot(epochs, losses[loss], 'r.-')
        err = plt.plot(epochs, losses[loss], 'b.-')
        plt.setp(err, linewidth=2.5)
        plt.ylabel(loss.capitalize(), fontsize=16)
        plt.xlabel('Epoch', fontsize=16)
        ax1.tick_params(labelsize=8)
        plt.hold(False)
        plt.grid()
    plt.subplots_adjust(
        left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=0.5)
    pyl.savefig(plot_file, dpi=100)


# ==================================================================#
# ==================================================================# 
Example 22
Project: geoist   Author: igp-gravity   File: gridder_obj.py    License: MIT License 5 votes vote down vote up
def map2DGrid(ax, grid, tstr, xlen=1.0, ylen=1.0, isLeft=False):
    """
    grid is a Grid2D object 
    """
    xmin,xmax,ymin,ymax = grid.getBounds()
    pdata = grid.getData()
    nr,nc = pdata.shape
    lonrange = np.linspace(xmin,xmax,num=nc)
    latrange = np.linspace(ymin,ymax,num=nr)
    lon,lat = np.meshgrid(lonrange,latrange)
    latmean = np.mean([ymin,ymax])
    lonmean = np.mean([xmin,xmax])
    m = Basemap(llcrnrlon=xmin,llcrnrlat=ymin,urcrnrlon=xmax,urcrnrlat=ymax,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='c',area_thresh=1000.,projection='lcc',\
            lat_1=latmean,lon_0=lonmean,ax=ax)
    # draw coastlines and political boundaries.
    m.drawcoastlines()
    #m.drawcountries()
    #m.drawstates()
    lons = np.arange(xmin,xmax,xlen)
    lats = np.arange(ymin,ymax,ylen)
    if isLeft:
        labels = labels=[1,0,0,0]
    else:
        labels = labels=[0,0,0,0]
    m.drawparallels(lats,labels=labels,color='white',fmt='%.1f') # draw parallels
    m.drawmeridians(lons,labels=[0,0,0,1],color='white',fmt='%.1f') # draw meridians
    pmesh = m.pcolormesh(lon,lat,np.flipud(grid.getData()),latlon=True)
    #plt.hold(True)
    ax.set_title(tstr)
    m.colorbar(pmesh) 
Example 23
Project: abu   Author: bbfamily   File: ABuTradeDrawer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot_bk_xd(bk_summary, kl_pd_xd_mean, title=None):
    """根据有bk_summary属性的bk交易因子进行可视化,暂时未迁移完成"""
    plt.figure()
    plt.plot(list(range(0, len(kl_pd_xd_mean))), kl_pd_xd_mean['close'])
    for bk in bk_summary.bk_xd_obj_list:
        plt.hold(True)
        pc = 'r' if bk.break_sucess is True else 'g'
        plt.plot(bk.break_index, kl_pd_xd_mean['close'][bk.break_index], 'ro', markersize=12, markeredgewidth=1.5,
                 markerfacecolor='None', markeredgecolor=pc)
    if title is not None:
        plt.title(title)
    plt.grid(True) 
Example 24
Project: abu   Author: bbfamily   File: ABuTradeDrawer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot_kp_xd(kp_summary, kl_pd_xd_mean, title=None):
    """根据有bk_summary属性的kp交易因子进行可视化,暂时未迁移完成"""
    plt.figure()
    plt.plot(list(range(0, len(kl_pd_xd_mean))), kl_pd_xd_mean['close'])

    for kp in kp_summary.kp_xd_obj_list:
        plt.hold(True)
        plt.plot(kp.break_index, kl_pd_xd_mean['close'][kp.break_index], 'ro', markersize=8, markeredgewidth=1.5,
                 markerfacecolor='None', markeredgecolor='r')

    if title is not None:
        plt.title(title)
    plt.grid(True) 
Example 25
Project: PCWG   Author: PCWG   File: plots.py    License: MIT License 5 votes vote down vote up
def plotPowerCurveSensitivity(self, sensCol):
        try:
            df = self.analysis.powerCurveSensitivityResults[sensCol].reset_index()
            from matplotlib import pyplot as plt
            plt.ioff()
            fig = plt.figure(figsize = (12,5))
            fig.suptitle('Power Curve Sensitivity to %s' % sensCol)
            ax1 = fig.add_subplot(121)
            ax1.hold(True)
            ax2 = fig.add_subplot(122)
            ax2.hold(True)
            power_column = self.analysis.measuredTurbulencePower if self.analysis.turbRenormActive else self.analysis.actualPower
            for label in self.analysis.sensitivityLabels.keys():
                filt = df['Bin'] == label
                ax1.plot(df['Wind Speed Bin'][filt], df[power_column][filt], label = label, color = self.analysis.sensitivityLabels[label])
                ax2.plot(df['Wind Speed Bin'][filt], df['Energy Delta MWh'][filt], label = label, color = self.analysis.sensitivityLabels[label])
            ax1.set_xlabel('Wind Speed (m/s)')
            ax1.set_ylabel('Power (kW)')
            ax2.set_xlabel('Wind Speed (m/s)')
            ax2.set_ylabel('Energy Difference from Mean (MWh)')
            box1 = ax1.get_position()
            box2 = ax2.get_position()
            ax1.set_position([box1.x0 - 0.05 * box1.width, box1.y0 + box1.height * 0.17,
                         box1.width * 0.95, box1.height * 0.8])
            ax2.set_position([box2.x0 + 0.05 * box2.width, box2.y0 + box2.height * 0.17,
                         box2.width * 1.05, box2.height * 0.8])
            handles, labels = ax1.get_legend_handles_labels()
            fig.legend(handles, labels, loc='lower center', ncol = len(self.analysis.sensitivityLabels.keys()), fancybox = True, shadow = True)
            file_out = self.path + os.sep + 'Power Curve Sensitivity to %s.png' % sensCol
            chckMake(self.path)
            fig.savefig(file_out)
            plt.close()
        except:
            Status.add("Tried to make a plot of power curve sensitivity to %s. Couldn't." % sensCol, verbosity=2) 
Example 26
Project: MinutiaeNet   Author: luannd   File: MinutiaeNet_utils.py    License: MIT License 5 votes vote down vote up
def draw_minutiae_overlay(image, minutiae, mnt_gt, fname, saveimage= False, r=15, drawScore=False):
    image = np.squeeze(image)
    fig = plt.figure()
    

    plt.imshow(image,cmap='gray')
    plt.hold(True)

    if mnt_gt.shape[1] > 3:
        mnt_gt = mnt_gt[:,:3]

    if mnt_gt.shape[0] > 0:
        if mnt_gt.shape[1] > 3:
            mnt_gt = mnt_gt[:, :3]
        plt.plot(mnt_gt[:, 0], mnt_gt[:, 1], 'bs', fillstyle='none', linewidth=1)
        for x, y, o in mnt_gt:
            plt.plot([x, x+r*np.cos(o)], [y, y+r*np.sin(o)], 'b-')

    if minutiae.shape[0] > 0:
        plt.plot(minutiae[:, 0], minutiae[:, 1], 'rs', fillstyle='none', linewidth=1)
        for x, y, o in minutiae:
            plt.plot([x, x+r*np.cos(o)], [y, y+r*np.sin(o)], 'r-')
            if drawScore == True:
                plt.text(x - 10, y - 10, '%.2f' % s, color='yellow', fontsize=4)

    plt.axis([0,image.shape[1],image.shape[0],0])
    plt.axis('off')
    plt.show()
    if saveimage:
        plt.savefig(fname, dpi=500, bbox_inches='tight')
        plt.close(fig)
    else:
        plt.show()
    return 
Example 27
Project: MinutiaeNet   Author: luannd   File: MinutiaeNet_utils.py    License: MIT License 5 votes vote down vote up
def draw_minutiae_overlay_with_score(image, minutiae, mnt_gt, fname, saveimage=False, r=15):
    image = np.squeeze(image)
    fig = plt.figure()

    plt.imshow(image, cmap='gray')
    plt.hold(True)


    if mnt_gt.shape[0] > 0:
        plt.plot(mnt_gt[:, 0], mnt_gt[:, 1], 'bs', fillstyle='none', linewidth=1)
        if mnt_gt.shape[1] > 3:
            for x, y, o, s in mnt_gt:
                plt.plot([x, x + r * np.cos(o)], [y, y + r * np.sin(o)], 'b-')
                plt.text(x - 10, y - 5, '%.2f' % s, color='green', fontsize=4)
        else:
            for x, y, o in mnt_gt:
                plt.plot([x, x + r * np.cos(o)], [y, y + r * np.sin(o)], 'b-')

    if minutiae.shape[0] > 0:
        plt.plot(minutiae[:, 0], minutiae[:, 1], 'rs', fillstyle='none', linewidth=1)
        for x, y, o, s in minutiae:
            plt.plot([x, x + r * np.cos(o)], [y, y + r * np.sin(o)], 'r-')
            plt.text(x-10,y-10,'%.2f'%s,color='yellow',fontsize=4)

    plt.axis([0, image.shape[1], image.shape[0], 0])
    plt.axis('off')

    if saveimage:
        plt.savefig(fname, dpi=500, bbox_inches='tight')
        plt.close(fig)
    else:
        plt.show()
    return 
Example 28
Project: MinutiaeNet   Author: luannd   File: MinutiaeNet_utils.py    License: MIT License 5 votes vote down vote up
def draw_ori_on_img(img, ori, mask, fname, saveimage=False, coh=None, stride=16):
    ori = np.squeeze(ori)
    #mask = np.squeeze(np.round(mask))

    img = np.squeeze(img)
    ori = ndimage.zoom(ori, np.array(img.shape)/np.array(ori.shape, dtype=float), order=0)
    if mask.shape != img.shape:
        mask = ndimage.zoom(mask, np.array(img.shape)/np.array(mask.shape, dtype=float), order=0)
    if coh is None:
        coh = np.ones_like(img)
    fig = plt.figure()
    plt.imshow(img,cmap='gray')
    plt.hold(True)  
    for i in xrange(stride,img.shape[0],stride):
        for j in xrange(stride,img.shape[1],stride):
            if mask[i, j] == 0:
                continue
            x, y, o, r = j, i, ori[i,j], coh[i,j]*(stride*0.9)
            plt.plot([x, x+r*np.cos(o)], [y, y+r*np.sin(o)], 'r-')
    plt.axis([0,img.shape[1],img.shape[0],0])
    plt.axis('off')
    if saveimage:
        plt.savefig(fname, bbox_inches='tight')
        plt.close(fig)
    else:
        plt.show()
    return 
Example 29
Project: cnn-levelset   Author: wiseodd   File: segmenter.py    License: MIT License 4 votes vote down vote up
def levelset_segment(img, phi=None, dt=1, v=1, sigma=1, alpha=1, n_iter=80, print_after=None):
    img_ori = img.copy()
    img = color.rgb2gray(img)

    img_smooth = scipy.ndimage.filters.gaussian_filter(img, sigma)

    g = stopping_fun(img_smooth, alpha)
    dg = op.grad(g)

    if phi is None:
        phi = default_phi(img)

    for i in range(n_iter):
        dphi = op.grad(phi)
        dphi_norm = op.norm(dphi)
        kappa = op.curvature(phi)

        smoothing = g * kappa * dphi_norm
        balloon = g * dphi_norm * v
        attachment = op.dot(dphi, dg)

        dphi_t = smoothing + balloon + attachment

        # Solve level set geodesic equation PDE
        phi = phi + dt * dphi_t

        if print_after is not None and i != 0 and i % print_after == 0:
            plt.imshow(img_ori, cmap='Greys_r')
            plt.hold(True)
            plt.contour(phi, 0, colors='r', linewidths=[3])
            plt.draw()
            plt.hold(False)
            plt.show()

    if print_after is not None:
        plt.imshow(img_ori, cmap='Greys_r')
        plt.hold(True)
        plt.contour(phi, 0, colors='r', linewidths=[3])
        plt.draw()
        plt.hold(False)
        plt.show()

    return (phi < 0) 
Example 30
Project: assaytools   Author: choderalab   File: analysis.py    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
def generate_plots(self, mcmc, map_fit=None, pdf_filename=None):
        """
        Generate interactive or PDF plots from MCMC trace.

        Parameters
        ----------
        mcmc : pymc.MCMC
           MCMC samples to plot
        map_fit : pymc.MAP, optional, default=None
           Plot the maximum a posteriori (MAP) estimate if provided.
        pdf_filename : str, optional, default=None
           If specified, generate a PDF containing plots.

        """
        alpha = 0.95 # confidence interval width
        print('')
        print('Generating plots...')
        from scipy.stats import bayes_mvs
        with PdfPages(pdf_filename) as pdf:
            for group in self.parameter_names:
                print(group)
                for name in self.parameter_names[group]:
                    try:
                        if map_fit:
                            mle = getattr(map_fit, name).value
                        else:
                            mle = getattr(mcmc, name).trace().mean()
                        trace = getattr(mcmc, name).trace()
                        mean_cntr, var_cntr, std_cntr = bayes_mvs(trace, alpha=alpha)
                        (center, (lower, upper)) = mean_cntr
                        if trace.std() == 0.0:
                            lower = upper = trace[0]

                        plt.figure(figsize=(12, 8))
                        plt.hold(True)
                        niterations = len(trace)
                        plt.plot([0, niterations], [mle, mle], 'r-')
                        plt.plot(trace, 'k.')
                        plt.xlabel('iteration')
                        plt.ylabel(name)
                        plt.title(name)
                        pdf.savefig()
                        plt.close()

                    except AttributeError as e:
                        pass