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

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

项目:lang-reps    作者:chaitanyamalaviya    | 项目源码 | 文件源码
def plot_sent_trajectories(sents, decode_plot):

    font = {'family' : 'normal',
            'size'   : 14}

    matplotlib.rc('font', **font) 
    i = 0    
    l = ["Portuguese","Catalan"]

    axes = plt.gca()
    #axes.set_xlim([xmin,xmax])
    axes.set_ylim([-1,1])

    for sent, enc in zip(sents, decode_plot):
    if i==2: continue
        i += 1
        #times = np.arange(len(enc))
        times = np.linspace(0,1,len(enc))
        plt.plot(times, enc, label=l[i-1])
    plt.title("Hidden Node Trajectories")
    plt.xlabel('timestep')
    plt.ylabel('trajectories')
    plt.legend(loc='best')
    plt.savefig("final_tests/cr_por_cat_hidden_cell_trajectories", bbox_inches="tight")
    plt.close()
项目:hippylib    作者:hippylib    | 项目源码 | 文件源码
def plot_pts(points, values, colorbar=True, subplot_loc=None, mytitle=None, show_axis='on', vmin=None, vmax=None, xlim=(0,1), ylim=(0,1)):
    if subplot_loc is not None:
        plt.subplot(subplot_loc)

    pp = plt.scatter(points[:,0], points[:,1], c=values.get_local(), marker=",", s=20, vmin=vmin, vmax=vmax)

    plt.axis(show_axis)

    if colorbar:
        plt.colorbar(pp, fraction=.1, pad=0.2)
    else:
        plt.gca().set_aspect('equal')

    if mytitle is not None:
        plt.title(mytitle, fontsize=20)

    if xlim is not None:
        plt.xlim(xlim)

    if ylim is not None:
        plt.ylim(ylim)

    return pp
项目:dpl    作者:ppengtang    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:py-faster-rcnn-tk1    作者:joeking11829    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:treecat    作者:posterior    | 项目源码 | 文件源码
def plot_chord(begin, end, spacing, color, alpha=None):
    """Plots a circular chord from begin to end.

    This assumes that the outer circle is centered at (0,0).

    Args:
        begin: A [2]-shaped numpy array.
        end: A [2]-shaped numpy array.
        spacing: A float, extra spacing around the edge of the circle.
        color: A matplotlib color spec.
        apha: A float or None.
    """
    # Adapted from https://matplotlib.org/users/path_tutorial.html
    codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
    xy = np.array([begin, begin, end, end])
    dist = ((begin - end)**2).sum()**0.5
    xy[[1, 2], :] *= 1 - 2 / 3 * dist + 1 / 6 * dist**2 - spacing
    path = Path(xy, codes)
    patch = PathPatch(
        path, facecolor='none', edgecolor=color, lw=1, alpha=alpha)
    pyplot.gca().add_patch(patch)
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def main():
    Q = ModelStorage.load(MODEL_NAME)
    Q_ = (Q - Q.mean()) / (Q.max() - Q.min())

    fig, ax = plt.subplots()
    heatmap = ax.pcolor(Q_, cmap=plt.cm.YlOrBr, alpha=0.8)

    fig = plt.gcf()
    fig.set_size_inches(8, 8)
    ax.set_frame_on(False)

    ax.set_xticklabels([1, 2, 3, 4], minor=False)
    ax.grid(False)
    ax = plt.gca()

    fig.savefig('report.png')
项目:nelder_mead    作者:owruby    | 项目源码 | 文件源码
def plot2d_simplex(simplex, ind):
    fig_dir = "./"
    plt.cla()
    n = 1000
    x1 = np.linspace(-256, 1024, n)
    x2 = np.linspace(-256, 1024, n)
    X, Y = np.meshgrid(x1, x2)
    Z = np.sqrt(X ** 2 + Y ** 2)
    plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10)))
    plt.gca().set_aspect("equal")
    plt.xlim((-256, 768))
    plt.ylim((-256, 768))

    plt.plot([simplex[0].x[0], simplex[1].x[0]],
             [simplex[0].x[1], simplex[1].x[1]], color="#000000")
    plt.plot([simplex[1].x[0], simplex[2].x[0]],
             [simplex[1].x[1], simplex[2].x[1]], color="#000000")
    plt.plot([simplex[2].x[0], simplex[0].x[0]],
             [simplex[2].x[1], simplex[0].x[1]], color="#000000")
    plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
项目:mx-rfcn    作者:giorking    | 项目源码 | 文件源码
def visualize_gt_roidb(imdb, gt_roidb):
    """
    visualize gt roidb
    :param imdb: the imdb to be visualized
    :param gt_roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
    :return: None
    """
    import matplotlib.pyplot as plt
    import skimage.io
    for i in range(len(gt_roidb)):
        im_path = imdb.image_path_from_index(imdb.image_set_index[i])
        im = skimage.io.imread(im_path)
        roi_rec = gt_roidb[i]
        plt.imshow(im)
        for bbox, gt_class, overlap in zip(roi_rec['boxes'], roi_rec['gt_classes'], roi_rec['gt_overlaps']):
            box = plt.Rectangle((bbox[0], bbox[1]),
                                bbox[2] - bbox[0],
                                bbox[3] - bbox[1], fill=False,
                                edgecolor='g', linewidth=3)
            plt.gca().add_patch(box)
            plt.gca().text(bbox[0], bbox[1], imdb.classes[gt_class] + ' {}'.format(overlap[0, gt_class]), color='w')
        plt.show()
项目:adversarial-frcnn    作者:xiaolonw    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:adversarial-frcnn    作者:xiaolonw    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()
项目:monogreedy    作者:jinjunqi    | 项目源码 | 文件源码
def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if self.dataset['type'] == 'instances':
            ax = plt.gca()
            polygons = []
            color = []
            for ann in anns:
                c = np.random.random((1, 3)).tolist()[0]
                if type(ann['segmentation']) == list:
                    # polygon
                    for seg in ann['segmentation']:
                        poly = np.array(seg).reshape((len(seg)/2, 2))
                        polygons.append(Polygon(poly, True,alpha=0.4))
                        color.append(c)
                else:
                    # mask
                    mask = COCO.decodeMask(ann['segmentation'])
                    img = np.ones( (mask.shape[0], mask.shape[1], 3) )
                    if ann['iscrowd'] == 1:
                        color_mask = np.array([2.0,166.0,101.0])/255
                    if ann['iscrowd'] == 0:
                        color_mask = np.random.random((1, 3)).tolist()[0]
                    for i in range(3):
                        img[:,:,i] = color_mask[i]
                    ax.imshow(np.dstack( (img, mask*0.5) ))
            p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
            ax.add_collection(p)
        if self.dataset['type'] == 'captions':
            for ann in anns:
                print ann['caption']
项目:fast-rcnn-distillation    作者:xiaolonw    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:fast-rcnn-distillation    作者:xiaolonw    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()
项目:fast-rcnn-distillation    作者:xiaolonw    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()
项目:faster-rcnn-resnet    作者:Eniac-Xie    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:faster-rcnn-resnet    作者:Eniac-Xie    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()
项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show()
项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
    plt.clf()
    plt.axis(axes)  # axes = [x1, x2, y1, y2]
    plt.scatter(data[:, 0], data[:, 1])  # plotting just for clarity
    for i, txt in enumerate(data):
        plt.annotate(i, (data[i][0] + 0.05, data[i][1]))  # add labels

    # add lines for edges
    for edge in [e for e in ph.ripsComplex if len(e) == 2]:
        # print(edge)
        pt1, pt2 = [data[pt] for pt in [n for n in edge]]
        # plt.gca().add_line(plt.Line2D(pt1,pt2))
        line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
        plt.gca().add_line(line)

    # add triangles
    for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
        pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
        line = plt.Polygon([pt1, pt2, pt3], closed=False,
                           color="blue", alpha=0.3, fill=True, edgecolor=None)
        plt.gca().add_line(line)
    plt.show()
项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show()
项目:decode    作者:deshima-dev    | 项目源码 | 文件源码
def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs):
    """Plot PSD (Power Spectral Density).

    Args:
        data (np.ndarray): Input data.
        dt (float): Time between each data.
        ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
        overlap_half (bool): Split data to half-overlapped regions.
        ax (matplotlib.axes): Axis the figure is plotted on.
        kwargs (optional): Plot options passed to ax.plot().
    """
    if ax is None:
        ax = plt.gca()
    vk, psddata = psd(data, dt, ndivide, window, overlap_half)
    ax.loglog(vk, psddata, **kwargs)
    ax.set_xlabel('Frequency [Hz]', fontsize=20, color='grey')
    ax.set_ylabel('PSD', fontsize=20, color='grey')
    ax.legend()
项目:decode    作者:deshima-dev    | 项目源码 | 文件源码
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs):
    """Plot Allan variance.

    Args:
        data (np.ndarray): Input data.
        dt (float): Time between each data.
        tmax (float): Maximum time.
        ax (matplotlib.axes): Axis the figure is plotted on.
        kwargs (optional): Plot options passed to ax.plot().
    """
    if ax is None:
        ax = plt.gca()
    tk, allanvar = allan_variance(data, dt, tmax)
    ax.loglog(tk, allanvar, **kwargs)
    ax.set_xlabel('Time [s]', fontsize=20, color='grey')
    ax.set_ylabel('Allan Variance', fontsize=20, color='grey')
    ax.legend()
项目:matplotlib-hep    作者:ibab    | 项目源码 | 文件源码
def make_split(ratio, gap=0.12):
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    from matplotlib.ticker import MaxNLocator
    cax = plt.gca()
    box = cax.get_position()
    xmin, ymin = box.xmin, box.ymin
    xmax, ymax = box.xmax, box.ymax
    gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax)
    gs.update(hspace=gap)

    ax = plt.subplot(gs[0])
    plt.setp(ax.get_xticklabels(), visible=False)
    bx = plt.subplot(gs[1], sharex=ax)

    return ax, bx
项目:OASIS    作者:j-friedrich    | 项目源码 | 文件源码
def plot_trace(n=0, lg=False):
    plt.plot(trueC[n], c=col[2], clip_on=False, zorder=5, label='Truth')
    plt.plot(solution, c=col[0], clip_on=False, zorder=7, label='Estimate')
    plt.plot(y, c=col[7], alpha=.7, lw=1, clip_on=False, zorder=-10, label='Data')
    if lg:
        plt.legend(frameon=False, ncol=3, loc=(.1, .62), columnspacing=.8)
    spks = np.append(0, solution[1:] - g * solution[:-1])
    plt.text(800, 2.2, 'Correlation: %.3f' % (np.corrcoef(trueSpikes[n], spks)[0, 1]), size=24)
    plt.gca().set_xticklabels([])
    simpleaxis(plt.gca())
    plt.ylim(0, 2.85)
    plt.xlim(0, 1500)
    plt.yticks([0, 2], [0, 2])
    plt.xticks([300, 600, 900, 1200], ['', ''])


# init params
项目:reconstruction    作者:microelly2    | 项目源码 | 文件源码
def showHeightMap(x,y,z,zi):
    ''' show height map in maptplotlib '''
    zi=zi.transpose()

    plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
               extent=[ y.min(), y.max(),x.min(), x.max()])

    plt.colorbar()

    CS = plt.contour(zi,15,linewidths=0.5,colors='k',
               extent=[ y.min(), y.max(),x.min(), x.max()])
    CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, 
               extent=[ y.min(), y.max(),x.min(), x.max()])

    z=z.transpose()
    plt.scatter(y, x, c=z)

    # achsen umkehren
    #plt.gca().invert_xaxis()
    #plt.gca().invert_yaxis()

    plt.show()
    return
项目:luxpy    作者:ksmet1977    | 项目源码 | 文件源码
def plotUH(xyz0 = None, uhues = [0,1,2,3], cieobs = _cieobs, cspace = 'Yuv', axh = None,formatstr = ['yo-.','bo-.','ro-.','go-.'], excludefromlegend = ''):
    """ 
    Plot unique hue line from centerpoint xyz0 (Kuehni, CRA, 2013: uY,uB,uG: Table II: spectral lights; uR: Table IV: Xiao data)
    """
    hues = ['yellow','blue','red','green']
    cmf = _cmf['bar'][cieobs]
    p_y = cmf[0] == 577.0 #unique yellow,#Kuehni, CRA 2013 (mean, table IV: spectral data)
    p_b = cmf[0] == 472.0 #unique blue,Kuehni, CRA 2013 (mean, table IV: spectral data)
    p_g = cmf[0] == 514.0 #unique green, Kuehni, CRA 2013 (mean, table II: spectral data)
    p_r = cmf[0] == 650.0 #unique red, Kuehni, CRA 2013 (Xiao data, table IV: display data)
    xyz_y = 100.0*cmf[1:,p_y].T
    xyz_b = 100.0*cmf[1:,p_b].T
    xyz_g = 100.0*cmf[1:,p_g].T
    xyz_r = 100.0*cmf[1:,p_r].T
    xyz_uh = np.vstack((xyz_y,xyz_b,xyz_r,xyz_g))
    huniquehues = []
    if xyz0 is None:
        xyz0 = np.array([100.0,100.0,100.0])
    if axh is None:
        axh = plt.gca()
    for huenr in uhues:
        lab = colortf(np.vstack((xyz0,xyz_uh[huenr])),cspace)
        huh = axh.plot(lab[:,1],lab[:,2],formatstr[huenr],label = excludefromlegend + 'Unique '+ hues[huenr])
        huniquehues = [huniquehues,huh]
    return  huniquehues
项目:luxpy    作者:ksmet1977    | 项目源码 | 文件源码
def plot_color_data(x,y,z=None, axh=None, show = True, cieobs =_cieobs, cspace = _cspace,  formatstr = 'k-', **kwargs):
    """
    Plot data.
    """

    if 'grid' in kwargs.keys():
        plt.grid(kwargs['grid']);kwargs.pop('grid')
    if z is not None:
        plt.plot(x,y,z,formatstr, linewidth = 2)
        plt.xlabel(_cspace_axes[cspace][0], kwargs)
    else:
        plt.plot(x,y,formatstr,linewidth = 2)

    plt.xlabel(_cspace_axes[cspace][1], kwargs)
    plt.ylabel(_cspace_axes[cspace][2], kwargs)

    if show == True:
        plt.show()
    else:
        return plt.gca()
项目: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()
项目:pyoptflow    作者:scivision    | 项目源码 | 文件源码
def compareGraphs(u,v,Inew,scale=3, quivstep=5):
    """
    makes quiver
    """
    if figure is None:
        return

    ax = figure().gca()
    ax.imshow(Inew,cmap = 'gray', origin='lower')
    # plt.scatter(POI[:,0,1],POI[:,0,0])
    for i in range(0,len(u), quivstep):
        for j in range(0,len(v), quivstep):
            ax.arrow(j,i, v[i,j]*scale, u[i,j]*scale, color='red',
                     head_width=0.5, head_length=1)

    # plt.arrow(POI[:,0,0],POI[:,0,1],0,-5)

    draw(); pause(0.01)
项目:py-faster-rcnn-tk1    作者:joeking11829    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()
项目:F_UNCLE    作者:fraserphysics    | 项目源码 | 文件源码
def test_eos_bounds_plot_vol(self):
        """Plots the extrapolated behaviour
        """

        eos = EOSModel(self.p_fun)

        test_vol = np.linspace(0.01, 1.0, 200)

        fig = plt.figure()
        ax1 = fig.gca()
        ax1.plot(test_vol, eos(test_vol))

        for i in range(5):
            old_dof = eos.get_dof()
            old_dof[i] *= 1.02
            new_eos = eos.update_dof(old_dof)
            ax1.plot(test_vol, new_eos(test_vol))
        # end

        ax1.set_xlabel('Specific volume / cm3 g-1')
        ax1.set_ylabel('Pressure / Pa')
        fig.savefig('vol_eos_bounds_test.pdf')
项目:probability_GAN    作者:MaureenZOU    | 项目源码 | 文件源码
def saveFig(realDtb, fakeDtb, discriminator, outDir):
        axes = plt.gca()
        axes.set_xlim([-1,10])
        axes.set_ylim([0,0.6])
        axes.set_autoscale_on(False)

        plt.axhline(y = discriminator)
        plt.plot()

        real_mean = np.mean(realDtb)
        real_std = np.std(realDtb)
        real_pdf = norm.pdf(realDtb, real_mean, real_std)
        plt.plot(realDtb, real_pdf)

        fake_mean = np.mean(fakeDtb)
        fake_std = np.std(fakeDtb)
        fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std)
        plt.plot(fakeDtb, fake_pdf)

        plt.savefig(outDir)
项目:probability_GAN    作者:MaureenZOU    | 项目源码 | 文件源码
def view(realDtb, fakeDtb, discriminator, outDir):
        plt.clf()

        axes = plt.gca()
        axes.set_xlim([-1,10])
        axes.set_ylim([0,0.6])
        axes.set_autoscale_on(False)

        plt.axhline(y = discriminator)
        plt.plot()

        real_mean = np.mean(realDtb)
        real_std = np.std(realDtb)
        real_pdf = norm.pdf(realDtb, real_mean, real_std)
        plt.plot(realDtb, real_pdf)

        fake_mean = np.mean(fakeDtb)
        fake_std = np.std(fakeDtb)
        fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std)
        plt.plot(fakeDtb, fake_pdf)

        plt.pause(0.00001)
项目:Odin    作者:JamesBrofos    | 项目源码 | 文件源码
def rolling_sharpe(self, window, fund, ax=None):
        if ax is None:
            ax = plt.gca()

        for i, p in enumerate(fund.fund_handler.portfolios):
            rets = p.history.returns.rolling(window=window)
            rs = compute_sharpe_ratio(rets)
            ax.plot(
                rs.index, rs, lw=2.,
                label=p.portfolio_handler.portfolio_id.title()
            )

        ax.set_xlabel("Date", fontsize=15.)
        ax.set_ylabel(
            "Rolling Sharpe Ratio ({})".format(window), fontsize=15.
        )
        ax.legend(loc="upper left")
        ax.grid(True)

        return ax
项目:Odin    作者:JamesBrofos    | 项目源码 | 文件源码
def equity(self, fund, ax=None):
        if ax is None:
            ax = plt.gca()

        for i, p in enumerate(fund.fund_handler.portfolios):
            ax.plot(
                p.history.equity.index, p.history.equity, lw=2.,
                label=p.portfolio_handler.portfolio_id.title()
            )
            ax.grid()

        ax.set_xlabel("Date", fontsize=15.)
        ax.set_ylabel("Equity", fontsize=15.)
        ax.legend(loc="upper left")
        ax.grid(True)

        return ax
项目:Odin    作者:JamesBrofos    | 项目源码 | 文件源码
def positions(self, fund, ax=None):
        if ax is None:
            ax = plt.gca()

        for i, p in enumerate(fund.fund_handler.portfolios):
            ax.plot(
                p.history.n_positions.index, p.history.n_positions, lw=2.,
                label=p.portfolio_handler.portfolio_id.title()
            )
            ax.grid()

        ax.set_xlabel("Date", fontsize=15.)
        ax.set_ylabel("Number of Positions", fontsize=15.)
        ax.legend(loc="upper left")
        ax.grid(True)

        return ax
项目:Odin    作者:JamesBrofos    | 项目源码 | 文件源码
def drawdown_percentage(self, fund, ax=None):
        if ax is None:
            ax = plt.gca()

        for i, p in enumerate(fund.fund_handler.portfolios):
            dd, dur = compute_drawdowns(p.history.equity, False)
            ax.plot(
                dd.index, dd, lw=2.,
                label=p.portfolio_handler.portfolio_id.title()
            )
            ax.grid()

        ax.set_xlabel("Date", fontsize=15.)
        ax.set_ylabel("Drawdown Percentage", fontsize=15.)
        ax.legend(loc="upper left")
        ax.grid(True)

        return ax
项目:Epileptic-Seizure-Prediction    作者:cedricsimar    | 项目源码 | 文件源码
def pretty_spectrogram(spectrogram):

    """
    Gent Master thesis spectrogram plot function
    """

    spectrogram = np.transpose(spectrogram, (2,1,0))

    ax = plt.gca()
    ax.set_yticks(range(0,6))
    ax.set_yticklabels([ 'delta', 'theta', 'alpha',
                        'beta', 'low-gamma', 'high-gamma'])
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(20)
    ax.set_xticks(range(0,10))
    ax.set_xticklabels(range(0,10))
    plt.imshow(spectrogram[0, :, :], aspect='auto', origin='lower', interpolation='none')
    cbar = plt.colorbar()
    cbar.ax.tick_params(labelsize=20)
    plt.xlabel('Time, Epoch', fontsize=20)
    plt.show()
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def generate_plot(plot_dir, iteration, data_in, output_g, output_d, train_data, args):
    data_in = data_in.squeeze()
    generated = output_g['generated']
    plt.plot(data_in[0], data_in[1], 'gx')
    plt.plot(generated[0], generated[1], 'r.')
    plt.xlim([-2, 2])
    plt.ylim([-2, 2])
    plt.gca().set_aspect('equal', adjustable='box')
    plt.axis('off')
    title = 'Iteration {} \n Gen. Cost {:.2E}  Disc. Cost {:.2E}'.format(
        iteration, float(output_g['batch_cost']), float(output_d['batch_cost']))
    plt.title(title)
    plt.savefig(plot_dir + '/' + str(iteration) + 'Generated.png')
    plt.clf()

    # plot and save loss and gradients
    for key in train_data.keys():
        data = np.array(train_data[key]).T
        plt.plot(data[0], data[1])
        plt.title(key + ' for ' + args.loss_type)
        plt.xlabel('Iterations')
        plt.ylabel(key)
        plt.savefig(plot_dir + '/' + key + '.png')
        plt.clf()
项目:PorousMediaLab    作者:biogeochemistry    | 项目源码 | 文件源码
def saturation_index_countour(lab, elem1, elem2, Ks, labels=False):
    plt.figure()
    plt.title('Saturation index %s%s' % (elem1, elem2))
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    plt.xlabel('Time')
    z = np.log10((lab.species[elem1]['concentration'][:, ::n] + 1e-8) * (
        lab.species[elem2]['concentration'][:, ::n] + 1e-8) / lab.constants[Ks])
    lim = np.max(abs(z))
    lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[::n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette(
        "RdBu_r", 101)), origin='lower', levels=lim, extend='both')
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    # cbar = plt.colorbar(CS)
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Saturation index %s%s' % (elem1, elem2))
    return ax
项目:PorousMediaLab    作者:biogeochemistry    | 项目源码 | 文件源码
def plot_profile(lab, element):
    plt.figure()
    plt.plot(lab.profiles[element], -lab.x,
             sns.xkcd_rgb["denim blue"], lw=3, label=element)
    if element == 'Temperature':
        plt.title('Temperature profile')
        plt.xlabel('Temperature, C')
    elif element == 'pH':
        plt.title('pH profile')
        plt.xlabel('pH')
    else:
        plt.title('%s concentration' % (element, ))
        plt.xlabel('Concentration')
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    ax.grid(linestyle='-', linewidth=0.2)
    plt.legend()
    plt.tight_layout()
    return ax
项目:PorousMediaLab    作者:biogeochemistry    | 项目源码 | 文件源码
def contour_plot_of_rates(lab, r, labels=False, last_year=False):
    plt.figure()
    plt.title('{}'.format(r))
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    if last_year:
        k = n - int(1 / lab.dt)
    else:
        k = 1
    z = lab.estimated_rates[r][:, k - 1:-1:n]
    # lim = np.max(np.abs(z))
    # lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[k::n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(
        sns.color_palette("Blues", 51)))
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Rate %s [M/V/T]' % r)
    return ax
项目:PorousMediaLab    作者:biogeochemistry    | 项目源码 | 文件源码
def contour_plot_of_delta(lab, element, labels=False, last_year=False):
    plt.figure()
    plt.title('Rate of %s consumption/production' % element)
    resoluion = 100
    n = math.ceil(lab.time.size / resoluion)
    if last_year:
        k = n - int(1 / lab.dt)
    else:
        k = 1
    z = lab.species[element]['rates'][:, k - 1:-1:n]
    lim = np.max(np.abs(z))
    lim = np.linspace(-lim - 0.1, +lim + 0.1, 51)
    X, Y = np.meshgrid(lab.time[k:-1:n], -lab.x)
    plt.xlabel('Time')
    CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette(
        "RdBu_r", 101)), origin='lower', levels=lim, extend='both')
    if labels:
        plt.clabel(CS, inline=1, fontsize=10, colors='w')
    cbar = plt.colorbar(CS)
    plt.ylabel('Depth')
    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)
    cbar.ax.set_ylabel('Rate of %s change $[\Delta/T]$' % element)
    return ax
项目:quadpy    作者:nschloe    | 项目源码 | 文件源码
def plot(scheme, interval=numpy.array([[-1.0], [1.0]]), show_axes=False):
    # change default range so that new disks will work
    plt.axis('equal')
    # ax.set_xlim((-1.5, 1.5))
    # ax.set_ylim((-1.5, 1.5))

    if not show_axes:
        plt.gca().set_axis_off()

    plt.plot(interval, [0, 0], color='k')

    pts = numpy.column_stack([scheme.points, numpy.zeros(len(scheme.points))])

    total_area = interval[1] - interval[0]
    helpers.plot_disks_1d(plt, pts, scheme.weights, total_area)
    return
项目:quadpy    作者:nschloe    | 项目源码 | 文件源码
def plot(scheme, show_axes=False):
    ax = plt.gca()
    # change default range so that new disks will work
    plt.axis('equal')
    ax.set_xlim((-1.5, 1.5))
    ax.set_ylim((-1.5, 1.5))

    if not show_axes:
        ax.set_axis_off()

    disk1 = plt.Circle((0, 0), 1, color='k', fill=False)
    ax.add_artist(disk1)

    helpers.plot_disks(
        plt, scheme.points, scheme.weights, numpy.pi
        )
    return
项目:quadpy    作者:nschloe    | 项目源码 | 文件源码
def plot(scheme, show_axes=False):
    ax = plt.gca()
    # change default range so that new disks will work
    plt.axis('equal')
    ax.set_xlim((-1.5, 1.5))
    ax.set_ylim((-1.5, 1.5))

    if not show_axes:
        ax.set_axis_off()

    disk1 = plt.Circle((0, 0), 1, color='k', fill=False)
    ax.add_artist(disk1)

    # The total area is used to gauge the disk radii. This is only meaningful
    # for 2D manifolds, not for the circle. What we do instead is choose the
    # total_area such that the sum of the disk radii equals pi.
    total_area = numpy.pi**3 / len(scheme.weights)
    helpers.plot_disks(
        plt, scheme.points, scheme.weights, total_area
        )
    return
项目:IDNNs    作者:ravidziv    | 项目源码 | 文件源码
def update_axes(axes, xlabel, ylabel, xlim, ylim, title, xscale, yscale, x_ticks, y_ticks, p_0, p_1
                ,font_size = 30, axis_font = 25,legend_font = 16 ):
    """adjust the axes to the ight scale/ticks and labels"""
    categories =6*['']
    labels = ['$10^{-5}$', '$10^{-4}$', '$10^{-3}$', '$10^{-2}$', '$10^{-1}$', '$10^0$', '$10^1$']
    #The legents of the mean and the std
    leg1 = plt.legend(p_0, categories, title=r'$\|Mean\left(\nabla{W_i}\right)\|$', loc='best',fontsize = legend_font,markerfirst = False, handlelength = 5)
    leg2 = plt.legend(p_1, categories, title=r'$STD\left(\nabla{W_i}\right)$', loc='best',fontsize = legend_font ,markerfirst = False,handlelength = 5)
    leg1.get_title().set_fontsize('21')  # legend 'Title' fontsize
    leg2.get_title().set_fontsize('21')  # legend 'Title' fontsize
    plt.gca().add_artist(leg1)
    plt.gca().add_artist(leg2)
    utils.adjustAxes(axes, axis_font=20, title_str='', x_ticks=x_ticks, y_ticks=y_ticks, x_lim=xlim, y_lim=ylim,
                     set_xlabel=True, set_ylabel=True, x_label=xlabel, y_label=ylabel, set_xlim=True, set_ylim=True,
                     set_ticks=True, label_size=font_size, set_yscale=True,
                     set_xscale=True, yscale=yscale, xscale=xscale, ytick_labels=labels, genreal_scaling=True)
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
def plot_streamlines(self, both=False, Hbot=None, Htop=None, R=None, **params):
        R = self.params.R if R is None else R
        Htop = self.params.Htop if Htop is None else Htop
        Hbot = self.params.Hbot if Hbot is None else Hbot
        #ax = plt.axes(xlim=(-R, R), ylim=(-Hbot, Htop))
        dolfin.parameters["allow_extrapolation"] = True
        if both:
            Fel, Fdrag = fields.get_functions("force_pointsize",
                                              "Fel", "Fdrag", **self.sim_params)
            streamlines(patches=[self.polygon_patches(), self.polygon_patches()],
                        R=R, Htop=Htop, Hbot=Hbot,
                        Nx=100, Ny=100, Fel=Fel, Fdrag=Fdrag, **params)
        else:
            streamlines(patches=[self.polygon_patches()],
                        R=R, Htop=Htop, Hbot=Hbot,
                        Nx=100, Ny=100, F=self.F, **params)
        dolfin.parameters["allow_extrapolation"] = False

#        for p in patches:
#            p.set_zorder(100)
#            plt.gca().add_patch(p)
        plt.xlim(-R, R)
        plt.ylim(-Hbot, Htop)
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def write_y(returns, image_filename):
    try:
        ax = plt.gca()
        ax.yaxis.grid(linestyle=':')

        assert returns is not None

        ret_plt = await aggregate_returns(returns=returns, convert_to='yearly') #* 100.0
        ret_plt.plot(kind="bar")
        ax.set_title('Yearly Returns, %', fontweight='bold')
        ax.set_ylabel('')
        ax.set_xlabel('')
        ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
        ax.xaxis.grid(False)
        plt.savefig(image_filename)
        plt.close()
        if settings.SHOW_DEBUG:
            print(colored.green("Wrote yearly graph {}".format(image_filename)))
    except Exception as err:
        print(colored.red("At write_yearly {}".format(err)))
项目:py-faster-rcnn-resnet-imagenet    作者:tianzhi0549    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show()
项目:py-faster-rcnn-resnet-imagenet    作者:tianzhi0549    | 项目源码 | 文件源码
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show()