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

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

项目:ward-metrics    作者:phev8    | 项目源码 | 文件源码
def plot_events_with_event_scores(gt_event_scores, detected_event_scores, ground_truth_events, detected_events, show=True):
    fig = plt.figure(figsize=(10, 3))
    for i in range(len(detected_events)):
        d = detected_events[i]
        plt.axvspan(d[0], d[1], 0, 0.5)
        plt.text((d[1] + d[0]) / 2, 0.2, detected_event_scores[i], horizontalalignment='center', verticalalignment='center')

    for i in range(len(ground_truth_events)):
        gt = ground_truth_events[i]
        plt.axvspan(gt[0], gt[1], 0.5, 1)
        plt.text((gt[1] + gt[0]) / 2, 0.8, gt_event_scores[i], horizontalalignment='center', verticalalignment='center')

    plt.tight_layout()

    if show:
        plt.show()
    else:
        plt.draw()
项目:PyGenAlg    作者:RaphDeau    | 项目源码 | 文件源码
def plotIndiv(indiv, i):
    ax = eval("ax" + str(i))
    ax.cla()
    ax.set_xticks(xTicks)
    ax.set_yticks(yTicks)
    ax.grid()
    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]
    for rectVertices, color in indiv.getAllObjectRect():
        path = Path(rectVertices, codes)
        patch = patches.PathPatch(path, facecolor=color, lw=2)
        ax.add_patch(patch)
    plt.draw()
项目:Wall-EEG    作者:neurotechuoft    | 项目源码 | 文件源码
def updatePlot(self, data):
        """ Update the plot """

        plt.figure(self.fig.number)  
        #assert (data.shape[1] == self.nbCh), 'new data does not have the same number of channels'
        #assert (data.shape[0] == self.nbPoints), 'new data does not have the same number of points'

        data = data - np.mean(data,axis=0)
        std_data = np.std(data,axis=0)
        std_data[np.where(std_data == 0)] = 1
        data = data/std_data*self.chRange/5.0     

        for i, chName in enumerate(self.chNames):
            self.chLinesDict[chName].set_ydata(data[:,i]+self.offsets[i])

        plt.draw()
项目:image-quantizer    作者:se7entyse7en    | 项目源码 | 文件源码
def render(self, show=True, new_figure=True):
        """Render the quantized image

        :param bool show: if the quantized image is also to be shown and not
                          only drawn.
        :param bool new_figure: if a new figure is to be used.

        """
        if new_figure:
            plt.figure()
            plt.clf()

        plt.title('{method} ({n_colors})'.format(
            method=self._method, n_colors=self._n_colors))
        plt.imshow(self._quantized_raster / 255.0)

        plt.draw()
        if show:
            plt.show()
项目:TickTickBacktest    作者:gavincyi    | 项目源码 | 文件源码
def plot_graph(cls, date_time, price, graph=None):
        """
        Plot the graph
        :param graph: MatPlotLibGraph
        :param date_time: Date time
        :param price: Price
        """
        date_time = (date_time - datetime.datetime(1970, 1, 1)).total_seconds()
        if graph is None:
            graph = plt.scatter([date_time], [price])
            plt.xlim([date_time, date_time + 60 * 60 * 24])
            # plt.ylim([float(price) * 0.95, float(price) * 1.05])
            plt.draw()
            plt.pause(0.1)
        else:
            array = graph.get_offsets()
            array = np.append(array, [date_time, price])
            graph.set_offsets(array)
            # plt.xlim([array[::2].min() - 0.5, array[::2].max() + 0.5])
            plt.ylim([float(array[1::2].min()) - 0.5, float(array[1::2].max()) + 0.5])
            plt.draw()
            plt.pause(0.1)

        return graph
项目:slitSpectrographBlind    作者:aasensio    | 项目源码 | 文件源码
def cellplot(fs, csf):
    """
    Plots PSF kernels

    --------------------------------------------------------------------------
    Usage:

    Call:  cellplot(fs, csf)

    Input: fs   PSF kernels, i.e. 3d array with kernels indexed by 0th index
           csf  size of kernels in x and y direction

    Output: Shows stack of PSF kernels arranged according to csf
    --------------------------------------------------------------------------

    Copyright (C) 2011 Michael Hirsch
    """    

    mp.clf()
    for i in range(np.prod(csf)):
        mp.subplot(csf[0],csf[1],i+1)
        mp.imshow(fs[i])
        mp.axis('off')
    mp.draw()
项目:usbtc08    作者:bankrasrg    | 项目源码 | 文件源码
def init_plot(self):
        # Interactive mode
        plt.ion()
        # Chart size and margins
        plt.figure(figsize = (20, 10))
        plt.subplots_adjust(hspace = 0.05, top = 0.95, bottom = 0.1, left = 0.05, right = 0.95)
        # Setup axis labels and ranges
        plt.title('Pico Technology TC-08')
        plt.xlabel('Time [s]')
        plt.ylabel('Temperature [' + self.unit_text + ']')
        plt.xlim(0, self.duration)
        self.plotrangemin = 19
        self.plotrangemax = 21
        plt.ylim(self.plotrangemin, self.plotrangemax)
        # Enable a chart line for each channel
        self.lines = []
        for i in CHANNEL_CONFIG:
            if CHANNEL_CONFIG.get(i) != ' ':
                self.lines.append(line(plt, CHANNEL_NAME.get(i)))
            else:
                self.lines.append(line(plt, 'Channel {:d} OFF'.format(i)))
        # Plot the legend
        plt.legend(loc = 'best', fancybox = True, framealpha = 0.5)
        plt.draw()
项目:zhusuan    作者:thu-ml    | 项目源码 | 文件源码
def draw(vmean, vlogstd):
        from scipy import stats
        plt.cla()
        xlimits = [-2, 2]
        ylimits = [-4, 2]

        def log_prob(z):
            z1, z2 = z[:, 0], z[:, 1]
            return stats.norm.logpdf(z2, 0, 1.35) + \
                stats.norm.logpdf(z1, 0, np.exp(z2))

        plot_isocontours(ax, lambda z: np.exp(log_prob(z)), xlimits, ylimits)

        def variational_contour(z):
            return stats.multivariate_normal.pdf(
                z, vmean, np.diag(np.exp(vlogstd)))

        plot_isocontours(ax, variational_contour, xlimits, ylimits)
        plt.draw()
        plt.pause(1.0 / 30.0)
项目:squeezenet-keras    作者:chasingbob    | 项目源码 | 文件源码
def update(self, conf_mat, classes, normalize=False):
        """This function prints and plots the confusion matrix.
        Normalization can be applied by setting `normalize=True`.
        """
        plt.imshow(conf_mat, interpolation='nearest', cmap=self.cmap)
        plt.title(self.title)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=45)
        plt.yticks(tick_marks, classes)

        if normalize:
            conf_mat = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]

        thresh = conf_mat.max() / 2.
        for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])):
            plt.text(j, i, conf_mat[i, j],                                          
                         horizontalalignment="center",
                         color="white" if conf_mat[i, j] > thresh else "black")

        plt.tight_layout()                                                    
        plt.ylabel('True label')                                              
        plt.xlabel('Predicted label')                                         
        plt.draw()
项目:Deep-Learning-Plugin    作者:flowjo-lakes    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        monitor.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig3.cla()
        #plot MMD target embbeding
        MMDtargetEmbeddingHandle = self.axFig3.scatter(self.MMDtargetEmbedding[:,0], self.MMDtargetEmbedding[:,1],
                                                        alpha=0.25, s=10, cmap='rainbow',
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netMMDLayerPredict(self.inputData)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig3.scatter(projection[:,0],projection[:,1], color='red', alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig3.legend(handles = (MMDtargetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:Deep-Learning-Plugin    作者:flowjo-lakes    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        Callback.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig.cla()
        #plot target embbeding
        targetEmbeddingHandle = self.axFig.scatter(self.targetEmbedding[:,0], self.targetEmbedding[:,1],
                                                        alpha=0.25, s=10, c=self.yTarget, cmap="rainbow",
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netAnchorLayerPredict(self.xInput)
        #print(plotPredictions)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig.scatter(projection[:,0],projection[:,1], 
                                            c=self.yInput, cmap="rainbow",
                                            alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig.legend(handles = (targetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def drawCenterMarker(self):

        """Draws a yellow marker in center of the image, making it 
        easier to find image center when selecting center of boundary."""

        centerImg=[self.img.shape[0]/2.,self.img.shape[1]/2.]

        if len(self.centerMarker)>0:
            self.clearCenterMarker()
        else:   
            pt=ptc.Circle(centerImg,radius=3,fill=True,color='y')
            self.centerMarker.append(self.ax.add_patch(pt))

        self.fig.canvas.draw()

        return self.centerMarker
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def redraw(ax):

    """Redraws axes's figure's canvas.

    Makes sure that current axes content is visible.

    Args:
        ax (matplotlib.axes): Matplotlib axes.

    Returns:
        matplotlib.axes: Matplotlib axes 

    """

    ax.get_figure().canvas.draw()

    return ax
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def showMeshIdx(self,ax=None):

        x,y,z=self.embryo.simulation.mesh.getCellCenters()

        if ax==None:
            fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["MeshIdx"],sup=self.name+" MeshIdx",proj=['3d'])
            ax=axes[0]

        #Somehow need to convert to np array since slicing does not work for fipy variables
        x=np.asarray(x)[self.meshIdx]
        y=np.asarray(y)[self.meshIdx]
        z=np.asarray(z)[self.meshIdx]

        ax.scatter(x,y,z,c=self.color)
        plt.draw()

        return ax
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def showMeshIdx2D(self,ax=None):



        x,y,z=self.embryo.simulation.mesh.getCellCenters()

        if ax==None:
            fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["MeshIdx"],sup=self.name+" MeshIdx")
            ax=axes[0]

        #Somehow need to convert to np array since slicing does not work for fipy variables
        x=np.asarray(x)[self.meshIdx]
        y=np.asarray(y)[self.meshIdx]

        ax.scatter(x,y,c=self.color)
        plt.draw()

        return ax
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def test_select_figure_formats_kwargs():
    ip = get_ipython()
    kwargs = dict(quality=10, bbox_inches='tight')
    pt.select_figure_formats(ip, 'png', **kwargs)
    formatter = ip.display_formatter.formatters['image/png']
    f = formatter.lookup_by_type(Figure)
    cell = f.__closure__[0].cell_contents
    nt.assert_equal(cell, kwargs)

    # check that the formatter doesn't raise
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot([1,2,3])
    plt.draw()
    formatter.enabled = True
    png = formatter(fig)
    assert png.startswith(_PNG)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def set_val(self, val):
        discrete_val = int(val / self.inc) * self.inc
        # We can't just call Slider.set_val(self, discrete_val), because this
        # will prevent the slider from updating properly (it will get stuck at
        # the first step and not "slide"). Instead, we'll keep track of the
        # the continuous value as self.val and pass in the discrete value to
        # everything else.
        xy = self.poly.xy
        xy[2] = discrete_val, 1
        xy[3] = discrete_val, 0
        self.poly.xy = xy
        self.valtext.set_text(self.valfmt % discrete_val)
        if self.drawon:
            self.ax.figure.canvas.draw()
        self.val = val
        if not self.eventson:
            return
        for cid, func in self.observers.items():
            func(discrete_val)
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
def displayResult(self):
        fig = plt.figure(101)
        plt.subplot(221)
        plt.imshow(np.abs(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Magnitude')
        plt.subplot(222)
        plt.imshow(np.angle(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Phase')
        plt.subplot(223)
        plt.imshow(np.abs(self.aperture),origin='lower')
        plt.title("Aperture Magnitude")
        plt.draw()
        plt.subplot(224)
        plt.imshow(np.angle(self.aperture),origin='lower')
        plt.title("Aperture Phase")
        plt.draw()
        fig.canvas.draw()


        #fig.tight_layout()
        # display.display(fig)
        # display.clear_output(wait=True)
        # time.sleep(.00001)
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
def fovPicker(self):
        fig = plt.figure()
        ax = plt.gca()
        plt.imshow(abs(self.fov))
        for n in np.arange(self.positions.shape[0]):
            circle = plt.Circle(self.positions[n, :], self.probe_radius, color='r', fill=False)
            ax.add_artist(circle)
        plt.title("After closing figure, enter desired position for in situ CDI measurement")
        fig.canvas.draw()

        index = input("Enter desired position for in situ CDI measurement: ")
        #print(index)
        #index = index.astype(int);
        index = int(index)

        self.fov_roi = crop_roi(image = self.fov,
                           crop_size = self.arr_size,
                           cenx = self.positions[index,1],
                           ceny = self.positions[index,0])

        return self.fov_roi
项目:PIE_ISAE_Essais_Vol    作者:YuanxiangFranck    | 项目源码 | 文件源码
def plot_segments_pie(seg, data, phases_colors):
    """
    Plot a pie chart of the percentage of time spent on each segment
    :param seg: dict
        dict with list of start, end for each segment
    :param data: pd.DataFrame
        the data
    """
    weights = get_weights(seg, data)
    plt.figure(1, figsize=(10, 10))
    labels = list(weights.keys())
    fracs = [weights[key] for key in labels]
    sum_weight = sum(weight for weight in fracs)
    if sum_weight < 1:
        fracs.append(1 - sum_weight)
        labels.append('missing')
    plot_colors = [phases_colors[name] for name in labels]
    plt.pie(fracs, labels=labels, colors=plot_colors, autopct='%1.1f%%')
    plt.title('Temps passé dans chaque phase, en pourcentage de la durée du vol', bbox={'facecolor':'0.8', 'pad':5})
    plt.draw()
    plt.show()
项目:rl-rc-car    作者:harvitronix    | 项目源码 | 文件源码
def visualize_polar(state):
    plt.clf()

    sonar = state[0][-1:]
    readings = state[0][:-1]

    r = []
    t = []
    for i, s in enumerate(readings):
        r.append(math.radians(i * 6))
        t.append(s)

    ax = plt.subplot(111, polar=True)

    ax.set_theta_zero_location('W')
    ax.set_theta_direction(-1)
    ax.set_ylim(bottom=0, top=105)

    plt.plot(r, t)
    plt.scatter(math.radians(90), sonar, s=50)
    plt.draw()
    plt.pause(0.1)
项目:Bicycle-Model    作者:caiofis    | 项目源码 | 文件源码
def readLine(self,pose,visualize = False):
        """Reads a line of the map based on the pose of the robot"""
        #Define the position of the first pixel
#        startx =  (pose[0] + d_cam*math.cos(math.radians(pose[2]))) + \
#         (self.L/2)*math.cos(math.radians((pose[2]+90)))
#        starty =  (pose[1] + d_cam*math.sin((pose[2]))) + \
#        (self.L/2)*math.sin(math.radians(pose[2]+90))
        startx = (pose[0] + self.d_start*math.cos(math.radians(pose[2]+self.beta)))
        starty = (pose[1] + self.d_start*math.sin(math.radians(pose[2]+self.beta)))
        x = []      #list of x positions of the pixels
        y = []      #list of y positions of the pixels
        reads = []  #value of the pixels

        for i in xrange(self.L):    #run over the line pixel by pixel
            x.append(int(startx+i*math.cos(math.radians(pose[2]-90))))
            y.append(int(starty+i*math.sin(math.radians(pose[2]-90))))
            reads.append(self.map.read(x[-1],y[-1]))
        if visualize:
            plt.plot(x,y)
            plt.draw()
        return reads
项目:python-study    作者:t2y    | 项目源码 | 文件源码
def main():
    args = parse_argument()
    log.debug(args)

    numbers = list(range(0, args.max_num + 1))
    notations = filter(lambda n: n.__name__ not in args.excludes, Notations)

    for notation in notations:
        notation().show(numbers)

    plt.title('Big-O Complexity')
    plt.xlabel('Growth of Input')
    plt.ylabel('Complexity')
    plt.legend(loc=2)

    plt.draw()
    plt.pause(1)
    handle_keyboard_interrupt()
项目:OTC3D    作者:tiffanyts    | 项目源码 | 文件源码
def scatter3d(self,title='',size=40,model=[]):
        """Returns a scatterplot of the pdcoord. Useful for visualizing 3D surface data """
        font = {'weight' : 'medium',
                'size'   : 22}
        #plt.rc('font', **font)
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d'); ax.pbaspect = [1, 1, 1] #always need pbaspect
        ax.set_title(title)
        p = ax.scatter(list(self.data.x), list(self.data.y),list(self.data.z),c = list(self.data.v),edgecolors='none', s=size, marker = ",", cmap ='jet')
        ax.view_init(elev=90, azim=-89)
        ax.set_xlabel('X axis'); ax.set_ylabel('Y axis'); ax.set_zlabel('Z axis')
        fig.colorbar(p)

        plt.draw()
        try:
            vertices = [(vertex.X(), vertex.Y(),vertex.Z()) for vertex in pyliburo.py3dmodel.fetch.vertex_list_2_point_list(pyliburo.py3dmodel.fetch.topos_frm_compound(model)["vertex"])]
            V1,V2,V3 = zip(*vertices)            
            p = ax.plot_wireframe(V1,V2,V3 )

        except TypeError:
            pass        

        return fig
项目:cartpole-q-learning    作者:YuriyGuts    | 项目源码 | 文件源码
def update_plot(self, episode_index):
        plot_right_edge = episode_index
        plot_left_edge = max(0, plot_right_edge - self.plot_episode_count)

        # Update point plot.
        x = range(plot_left_edge, plot_right_edge)
        y = self.lengths[plot_left_edge:plot_right_edge]
        self.point_plot.set_xdata(x)
        self.point_plot.set_ydata(y)
        self.ax.set_xlim(plot_left_edge, plot_left_edge + self.plot_episode_count)

        # Update rolling mean plot.
        mean_kernel_size = 101
        rolling_mean_data = np.concatenate((np.zeros(mean_kernel_size), self.lengths[plot_left_edge:episode_index]))
        rolling_means = pd.rolling_mean(
            rolling_mean_data,
            window=mean_kernel_size,
            min_periods=0
        )[mean_kernel_size:]
        self.mean_plot.set_xdata(range(plot_left_edge, plot_left_edge + len(rolling_means)))
        self.mean_plot.set_ydata(rolling_means)

        # Repaint the surface.
        plt.draw()
        plt.pause(0.0001)
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def compare2(experiments,measurename=None,which=(0,1)):
    """ draw a scatter plot to compare trial-by-trial results of two experiments."""
    if not measurename:
        measures = set([meas for exp in experiments for meas in exp.measures])
        if len(measures) == 1:
            measurename = measures.pop()
        elif len(measures)>1:
            raise Exception("Experiments have multiple measures, need to supply a measure name.")
        else:
            raise Exception("No measures? What?")
    plt.figure(figsize=fig_size)
    dataA = experiments[which[0]].getresults(measurename)
    dataB = experiments[which[1]].getresults(measurename)

    plt.scatter(dataA,dataB)
    dataab = np.sort(dataA+dataB)
    absmin = dataab[0]
    absmax = dataab[-1]
    plt.plot([absmin,absmax], [absmin,absmax],'--')

    plt.xlabel(measurename+", "+experiments[which[0]].name)
    plt.ylabel(measurename+", "+experiments[which[1]].name)
    plt.title("trial-by-trial comparison (pairs with same initial conditions)")
项目:BatchEffectRemoval    作者:ushaham    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        monitor.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig3.cla()
        #plot MMD target embbeding
        MMDtargetEmbeddingHandle = self.axFig3.scatter(self.MMDtargetEmbedding[:,0], self.MMDtargetEmbedding[:,1],
                                                        alpha=0.25, s=10, cmap='rainbow',
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netMMDLayerPredict(self.inputData)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig3.scatter(projection[:,0],projection[:,1], color='red', alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig3.legend(handles = (MMDtargetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:BatchEffectRemoval    作者:ushaham    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        Callback.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig.cla()
        #plot target embbeding
        targetEmbeddingHandle = self.axFig.scatter(self.targetEmbedding[:,0], self.targetEmbedding[:,1],
                                                        alpha=0.25, s=10, c=self.yTarget, cmap="rainbow",
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netAnchorLayerPredict(self.xInput)
        #print(plotPredictions)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig.scatter(projection[:,0],projection[:,1], 
                                            c=self.yInput, cmap="rainbow",
                                            alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig.legend(handles = (targetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def im(my_img,ax=None,**kwargs):
    "Displays image showing the values under the cursor."
    if ax is None:
        ax = plt.gca()
    def format_coord(x, y):
        x = np.int(x + 0.5)
        y = np.int(y + 0.5)
        val = my_img[y,x]
        try:
            return "%.4E @ [%4i, %4i]" % (val, x, y)
        except IndexError:
            return ""
    ax.imshow(my_img,interpolation='nearest',**kwargs)
    ax.format_coord = format_coord
    plt.colorbar()
    plt.draw()
    plt.show()
项目:recognizeFitExercise    作者:tyiannak    | 项目源码 | 文件源码
def dirClassificationSentiment(dirName, modelName, modelType):
    types = ('*.jpg', '*.png',)
    filesList = []
    for files in types:
        filesList.extend(glob.glob(os.path.join(dirName, files)))

    filesList = sorted(filesList)
    print filesList
    Features = []
    plt.close('all');    
    ax = plt.gca()
    plt.hold(True)
    for fi in filesList:
        P, classNames = fileClassification(fi, modelName, modelType)
        im = cv2.imread(fi, cv2.CV_LOAD_IMAGE_COLOR)    
        Width = 0.1;  Height = 0.1; startX = P[classNames.index("positive")]; startY = 0;
        myaximage = ax.imshow(cv2.cvtColor(im, cv2.cv.CV_RGB2BGR), extent=(startX-Width/2.0, startX+Width/2.0, startY-Height/2.0, startY+Height/2.0), alpha=1.0, zorder=-1)
        plt.axis((0,1,-0.1,0.1))
        plt.show(block = False);
        plt.draw()
    plt.show(block = True);
项目:Simulator    作者:libsmelt    | 项目源码 | 文件源码
def draw_loop():
    """
    Draw the graph in a loop

    """
    global G

    plt.ion()

    # mng = plt.get_current_fig_manager()
    # mng.resize(*mng.window.maxsize())
    plt.draw()

    for line in fileinput.input():
        if output(line):
            plt.clf()
            nx.draw(G)
            plt.draw()
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def test_select_figure_formats_kwargs():
    ip = get_ipython()
    kwargs = dict(quality=10, bbox_inches='tight')
    pt.select_figure_formats(ip, 'png', **kwargs)
    formatter = ip.display_formatter.formatters['image/png']
    f = formatter.lookup_by_type(Figure)
    cell = f.__closure__[0].cell_contents
    nt.assert_equal(cell, kwargs)

    # check that the formatter doesn't raise
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot([1,2,3])
    plt.draw()
    formatter.enabled = True
    png = formatter(fig)
    assert png.startswith(_PNG)
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def __call__(self, **kwargs):
        """
        Renders the plot for the given named slider values.

        Kwargs:

            The slider name and associated dimension index value.
            E.g. ::

                plot(time=5, model_level_number=23)

            The plot cube will be sliced on the associated 'time' and
            'model_level_number' dimensions at the specified index values
            before being rendered on its axes.

        """
        index = [slice(None)] * self.cube.ndim
        alias_by_dim = self._invert_mapping(self._dim_by_alias)
        for name, value in kwargs.items():
            # The alias has priority, so check this first.
            dim = self._dim_by_alias.get(name)
            if dim is None:
                dim = self._slider_dim_by_name.get(name)
                if dim is None:
                    emsg = '{!r} called with unknown name {!r}.'
                    raise ValueError(emsg.format(type(self).__name__, name))
                else:
                    if dim in alias_by_dim:
                        wmsg = ('{!r} expected to be called with alias {!r} '
                                'for dimension {}, rather than with {!r}.')
                        warnings.warn(wmsg.format(type(self).__name__,
                                                  alias_by_dim[dim], dim,
                                                  name))
            index[dim] = value
        index = tuple(index)
        key = tuple(sorted(kwargs.items()))
        # A primative weak reference cache.
        self.subcube = self.cache.setdefault(key, self.cube[index])
        return self.draw(self.subcube)
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def draw(self, cube):
        """Abstract method."""
        emsg = '{!r} requires a draw method for rendering.'
        raise NotImplementedError(emsg.format(type(self).__name__))
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def resize_colourbar(self, event):
        # Ensure axes position is up to date.
        self.axes.apply_aspect()
        posn = self.axes.get_position()
        extent = self.axes.get_extent()
        aspect = (extent[1] - extent[0]) / (extent[3] - extent[2])
        if aspect < 1.2:
            self.cbar_ax.set_position([posn.x1 + self.cb_sep, posn.y0,
                                       self.cb_depth, posn.height])
        else:
            self.cbar_ax.set_position([posn.x0, posn.y0 - 6*self.cb_sep,
                                       posn.width, 2*self.cb_depth])
        plt.draw()
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def draw(self, cube):
        self.element = iplt.contourf(cube, axes=self.axes, coords=self.coords,
                                     extend='both', **self.kwargs)
        if 'levels' not in self.kwargs:
            self.kwargs['levels'] = self.element.levels
        return self.element

    # XXX: Not sure this should live here!
    #      Need test coverage!
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def draw(self, cube):
        self.element = iplt.contour(cube, axes=self.axes, coords=self.coords,
                                    extend='both', **self.kwargs)
        if 'levels' not in self.kwargs:
            self.kwargs['levels'] = self.element.levels
        return self.element
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0],  X[:,1], X[:,2], color='red')
    ax.scatter(Y[:,0],  Y[:,1], Y[:,2], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0],  X[:,1], X[:,2], color='red')
    ax.scatter(Y[:,0],  Y[:,1], Y[:,2], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0],  X[:,1], X[:,2], color='red')
    ax.scatter(Y[:,0],  Y[:,1], Y[:,2], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0] ,  X[:,1], color='red')
    ax.scatter(Y[:,0] ,  Y[:,1], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0] ,  X[:,1], color='red')
    ax.scatter(Y[:,0] ,  Y[:,1], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0] ,  X[:,1], color='red')
    ax.scatter(Y[:,0] ,  Y[:,1], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:pycpd    作者:siavashk    | 项目源码 | 文件源码
def visualize(iteration, error, X, Y, ax):
    plt.cla()
    ax.scatter(X[:,0] ,  X[:,1], color='red')
    ax.scatter(Y[:,0] ,  Y[:,1], color='blue')
    plt.draw()
    print("iteration %d, error %.5f" % (iteration, error))
    plt.pause(0.001)
项目:HandDetection    作者:YunqiuXu    | 项目源码 | 文件源码
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    #fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def imshow_plt(label, im, block=True):
    global figures
    if label not in figures: 
        figures[label] = plt.imshow(im, interpolation=None, animated=True, label=label)
        plt.tight_layout()
        plt.axis('off')

    figures[label].set_data(im)
    # figures[label].canvas.draw()
    # plt.draw()
    plt.show(block=block)
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def bar_plt(label, ys, block=False):
    global figures
    if label not in figures:
        figures[label] = plt.bar(np.arange(len(ys)), ys, align='center')
        plt.title(label)
        # plt.tight_layout()
        # plt.axis('off')

    inds, = np.where([key == label for key in figures.keys()])
    for rect, y in zip(figures[label], ys): 
        rect.set_height(y)

    plt.draw()
    plt.show(block=block)
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def _finalize_plotting(self):
        from matplotlib import pyplot
        pyplot.tight_layout(rect=(0, 0, 0.96, 1))
        pyplot.draw()  # update "screen"
        pyplot.ion()  # prevents that the execution stops after plotting
        pyplot.show()
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def plot(self, plot_cmd=None, tf=lambda y: y):
        """plot the data we have, return ``self``"""
        from matplotlib import pyplot
        if not plot_cmd:
            plot_cmd = self.plot_cmd
        colors = 'bgrcmyk'
        pyplot.gcf().clear()
        res = self.res

        flatx, flatf = self.flattened()
        minf = np.inf
        for i in flatf:
            minf = min((minf, min(flatf[i])))
        addf = 1e-9 - minf if minf <= 1e-9 else 0
        for i in sorted(res.keys()):  # we plot not all values here
            if isinstance(i, int):
                color = colors[i % len(colors)]
                arx = sorted(res[i].keys())
                plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
                pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
                plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
        pyplot.ylabel('f + ' + str(addf))
        pyplot.draw()
        pyplot.ion()
        pyplot.show()
        return self
项目:multimodal_varinf    作者:tmoer    | 项目源码 | 文件源码
def plot_data(self,Data):

        self.fig = fig =  plt.figure()
        self.ax1 = ax1 = fig.add_subplot(311)
        self.ax2 = ax2 = fig.add_subplot(312)
        self.ax3 = ax3 = fig.add_subplot(313)

        ax1.scatter(Data.X,Data.Y,color='b')
        ax1.axis([-1, 1, -1, 7])
        plt.xlabel('S')
        plt.ylabel('S\'')
        plt.title('True data')

        new_dat, = ax2.plot([],[],'ko')
        self.new_dat = new_dat        
        ax2.axis([-1, 1, -1, 7])
        plt.xlabel('S')
        plt.ylabel('S\'')

        plt.subplot(313)
        new_dat_2, = ax3.plot([],[],'ro')
        self.new_dat_2 = new_dat_2
        self.t = np.zeros(300)
        self.lr = np.zeros(300)
        ax3.axis([0, 100000, 0, 0.01])
        plt.ylabel('learning rate')

        #plt.draw()
        #plt.show(block=False)