Python pylab.draw() Examples

The following are 30 code examples of pylab.draw(). 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 also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_click_yshift(axes = "gca"):
    """
    Takes a starting and ending point, then shifts the image y by this amount
    """
    if axes == "gca": axes = _pylab.gca()

    try:
        p1 = _pylab.ginput()
        p2 = _pylab.ginput()

        yshift = p2[0][1]-p1[0][1]

        e = axes.images[0].get_extent()

        e[2] = e[2] + yshift
        e[3] = e[3] + yshift

        axes.images[0].set_extent(e)

        _pylab.draw()
    except:
        print("whoops") 
Example #2
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def smooth_all_traces(smoothing=1, trim=True, axes="gca"):
    """

    This function does nearest-neighbor smoothing of the data

    """
    if axes=="gca": axes=_pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            smooth_line(line, smoothing, trim, draw=False)
    _pylab.draw() 
Example #3
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def line_math(fx=None, fy=None, axes='gca'):
    """
    applies function fx to all xdata and fy to all ydata.
    """

    if axes=='gca': axes = _pylab.gca()

    lines = axes.get_lines()

    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            xdata, ydata = line.get_data()
            if not fx==None: xdata = fx(xdata)
            if not fy==None: ydata = fy(ydata)
            line.set_data(xdata,ydata)

    _pylab.draw() 
Example #4
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def set_all_line_attributes(attribute="lw", value=2, axes="current", refresh=True):
    """

    This function sets all the specified line attributes.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            _pylab.setp(line, attribute, value)

    # update the plot
    if refresh: _pylab.draw() 
Example #5
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def apply(self, axes="gca"):
        """
        Applies the style cycle to the lines in the axes specified
        """

        if axes == "gca": axes = _pylab.gca()
        self.reset()
        lines = axes.get_lines()

        for l in lines:
            l.set_color(self.get_line_color(1))
            l.set_mfc(self.get_face_color(1))
            l.set_marker(self.get_marker(1))
            l.set_mec(self.get_edge_color(1))
            l.set_linestyle(self.get_linestyle(1))

        _pylab.draw() 
Example #6
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def reverse_draw_order(axes="current"):
    """

    This function takes the graph and reverses the draw order.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # reverse the order
    lines.reverse()

    for n in range(0, len(lines)):
        if isinstance(lines[n], _mpl.lines.Line2D):
            axes.lines[n]=lines[n]

    _pylab.draw() 
Example #7
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_set_clim(zmin=None, zmax=None, axes="gca"):
    """
    This will set the clim (range) of the colorbar.

    Setting zmin or zmax to None will not change them.
    Setting zmin or zmax to "auto" will auto-scale them to include all the data.
    """
    if axes=="gca": axes=_pylab.gca()

    image = axes.images[0]

    if zmin=='auto': zmin = _n.min(image.get_array())
    if zmax=='auto': zmax = _n.max(image.get_array())

    if zmin==None: zmin = image.get_clim()[0]
    if zmax==None: zmax = image.get_clim()[1]

    image.set_clim(zmin, zmax)

    _pylab.draw() 
Example #8
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_shift(xshift=0, yshift=0, axes="gca"):
    """
    This will shift an image to a new location on x and y.
    """

    if axes=="gca": axes = _pylab.gca()

    e = axes.images[0].get_extent()

    e[0] = e[0] + xshift
    e[1] = e[1] + xshift
    e[2] = e[2] + yshift
    e[3] = e[3] + yshift

    axes.images[0].set_extent(e)

    _pylab.draw() 
Example #9
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_coarsen(xlevel=0, ylevel=0, image="auto", method='average'):
    """
    This will coarsen the image data by binning each xlevel+1 along the x-axis
    and each ylevel+1 points along the y-axis

    type can be 'average', 'min', or 'max'
    """
    if image == "auto": image = _pylab.gca().images[0]

    Z = _n.array(image.get_array())

    # store this image in the undo list
    global image_undo_list
    image_undo_list.append([image, Z])
    if len(image_undo_list) > 10: image_undo_list.pop(0)

    # images have transposed data
    image.set_array(_fun.coarsen_matrix(Z, ylevel, xlevel, method))

    # update the plot
    _pylab.draw() 
Example #10
Source File: VOCpr.py    From face-magnet with Apache License 2.0 6 votes vote down vote up
def drawPrfast(tp, fp, tot, show=True, col="g"):
    tp = numpy.cumsum(tp)
    fp = numpy.cumsum(fp)
    rec = tp / tot
    prec = tp / (fp + tp)
    ap = VOColdap(rec, prec)
    ap1 = VOCap(rec, prec)
    if show:
        pylab.plot(rec, prec, '-%s' % col)
        pylab.title("AP=%.1f 11pt(%.1f)" % (ap1 * 100, ap * 100))
        pylab.xlabel("Recall")
        pylab.ylabel("Precision")
        pylab.grid()
        pylab.gca().set_xlim((0, 1))
        pylab.gca().set_ylim((0, 1))
        pylab.show()
        pylab.draw()
    return rec, prec, ap1 
Example #11
Source File: _plotting_mess.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def complex_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
    """
    Plots function(s) in the complex plane over the specified range.

    Parameters
    ----------
    f='1.0/(1+1j*x)'                 
        Complex-valued function or list of functions to plot. 
        These can be string functions or single-argument python functions;
        additional globals can be supplied by g.
    xmin=-1, xmax=1, steps=200   
        Range over which to plot and how many points to plot
    p='x'
        If using strings for functions, p is the independent parameter name.
    g=None               
        Optional dictionary of extra globals. Try g=globals()!
    erange=False              
        Use exponential spacing of the x data?

    See spinmob.plot.xy.data() for additional optional keyword arguments.
    """
    kwargs2 = dict(xlabel='Real', ylabel='Imaginary')
    kwargs2.update(kwargs)
    function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, complex_plane=True, draw=True, **kwargs2) 
Example #12
Source File: visualize.py    From pathnet-pytorch with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show(self, genes, color):
        if self.vis:
            self.get_fig(genes, color)
            pylab.draw()
            pause(0.05)
            pylab.clf()
            self.reset() 
Example #13
Source File: celllab_cts.py    From landlab with MIT License 5 votes vote down vote up
def update_plot(self):
        """Plot the current node state grid."""
        plt.clf()
        if self.gridtype == "rast":
            nsr = self.ca.grid.node_vector_to_raster(self.ca.node_state)
            plt.imshow(nsr, interpolation="None", origin="lower", cmap=self._cmap)
        else:
            self.ca.grid.hexplot(self.ca.node_state, color_map=self._cmap)

        plt.draw()
        plt.pause(0.001) 
Example #14
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def yscale(scale='log'):
    _pylab.yscale(scale)
    _pylab.draw() 
Example #15
Source File: build_diagram.py    From NEUCOGAR with GNU General Public License v2.0 5 votes vote down vote up
def voltage_diagram(times, voltages, name, path):
    """
    Function for making voltage diagrams
    :param times:    (dict) times
    :param voltages: (dict) voltages
    :param name:     (str) name of brain part
    :param path:     (str) path to save diagram
    :return: None
    """
    pylab.figure()
    line_style = ""

    if type(times) is dict:
        # for each neuron plot
        for key in times:
            pylab.plot(times[key], voltages[key], line_style, label=key)
    else:
        raise ValueError("Unsupported value")

    pylab.ylabel("Membrane potential (mV)")
    pylab.xlabel("Time (ms)")
    pylab.legend(loc="best")
    pylab.title("Voltage" + name)
    pylab.grid(True)
    pylab.draw()
    pylab.savefig("{0}{1}.png".format(path, name), dpi=dpi_n, format='png')
    pylab.close() 
Example #16
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def fatten_line(line, william_fatner=2.0):
    size  = line.get_markersize()
    width = line.get_linewidth()
    line.set_markersize(size*william_fatner)
    line.set_linewidth(width*william_fatner)
    _pylab.draw() 
Example #17
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def legend(location='best', fontsize=16, axes="gca"):
    if axes=="gca": axes = _pylab.gca()

    axes.legend(loc=location, prop=_mpl.font_manager.FontProperties(size=fontsize))
    _pylab.draw()




#
# Style cycle, available for use in plotting
# 
Example #18
Source File: build_diagram.py    From NEUCOGAR with GNU General Public License v2.0 5 votes vote down vote up
def spikes_diagram(ts, gids, name, path):
    """
    Function for making spike diagrams
    :param ts:   (list) times
    :param gids: (list) global IDs of neurons
    :param name: (str) name of brain part
    :param path: (str) path to save results
    :return: None
    """
    pylab.figure()
    color_marker = "."
    color_bar = "blue"
    color_edge = "black"
    ylabel = "Neuron ID"
    hist_binwidth = 5.0
    location = pylab.axes([0.1, 0.3, 0.85, 0.6])
    pylab.plot(ts, gids, color_marker)
    pylab.ylabel(ylabel)
    xlim = pylab.xlim()
    pylab.xticks([])
    pylab.axes([0.1, 0.1, 0.85, 0.17])
    t_bins = numpy.arange(numpy.amin(ts), numpy.amax(ts), hist_binwidth)
    n, bins = pylab.histogram(ts, bins=t_bins)
    num_neurons = len(numpy.unique(gids))
    heights = (1000 * n / (hist_binwidth * num_neurons))
    # FixMe t_bins[:-1] should work without cutting the end value
    pylab.bar(t_bins[:-1], heights, width=hist_binwidth, color=color_bar, edgecolor=color_edge)
    pylab.yticks([int(a) for a in numpy.linspace(0.0, int(max(heights) * 1.1) + 5, 4)])
    pylab.ylabel("Rate (Hz)")
    pylab.xlabel("Time (ms)")
    pylab.grid(True)
    pylab.axes(location)
    pylab.title(name)
    pylab.xlim(xlim)
    pylab.draw()
    pylab.savefig("{0}{1}.png".format(path, name), dpi=dpi_n, format='png')
    pylab.close() 
Example #19
Source File: recipe-576501.py    From code with MIT License 5 votes vote down vote up
def replotf(self):
		"""This replots the function given the coefficient array c."""

		x = M.arange(-1,1.,.001)
		M.ioff()
		M.figure(self.ffig.number)
		M.cla()
		M.plot(x, f(x,self.c))				
		M.title(fstring(self.c))
		M.draw() 
Example #20
Source File: recipe-576501.py    From code with MIT License 5 votes vote down vote up
def replotc(self):
		"""This replots the coefficients."""
	
		M.figure(self.cfig.number)
		M.ioff()
		for n in xrange(self.order-1):
			M.axes(self.ax[n])
			#M.cla()
			M.plot([self.c[n]], [self.c[n+1]],'ko')
			M.xlabel("$c_%d$" %(n))
			M.ylabel("$c_%d$" %(n+1))
			M.axis([-1, 1, -1, 1]);
			del self.ax[n].lines[0]

		M.draw() 
Example #21
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show(self):
        if not self.drawn: self.draw()
        import pylab
        pylab.show() 
Example #22
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def coarsen_line(line, level=2, exponential=False, draw=True):
    """
    Coarsens the specified line (see spinmob.coarsen_data() for more information).
    
    Parameters
    ----------
    line
        Matplotlib line instance.
    level=2
        How strongly to coarsen.
    exponential=False
        If True, use the exponential method (great for log-x plots).
    draw=True
        Redraw when complete.
    """

    # get the actual data values
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    xdata,ydata = _fun.coarsen_data(xdata, ydata, level=level, exponential=exponential)
    
    # don't do anything if we don't have any data left
    if len(ydata) == 0: print("There's nothing left in "+str(line)+"!")

    # otherwise set the data with the new arrays
    else: line.set_data(xdata, ydata)

    # we refresh in real time for giggles
    if draw: _pylab.draw() 
Example #23
Source File: recipe-577402.py    From code with MIT License 5 votes vote down vote up
def callback(*args):
   H.set_array(pylab.random((10,10)))
   pylab.draw()
   wx.WakeUpIdle() # ensure that the idle event keeps firing 
Example #24
Source File: recipe-577642.py    From code with MIT License 5 votes vote down vote up
def update(val):
  x = sx.val
  y = sy.val
  Z, set = compute_trajectory(x,y)
  l.set_xdata(Z.real)
  l.set_ydata(Z.imag)
  st.set_xdata(Z[0].real)
  st.set_ydata(Z[0].imag)  
  if set:
    m_set[0] += [x]
    m_set[1] += [y]
  ms.set_xdata(m_set[0])
  ms.set_ydata(m_set[1])  
  pylab.draw() 
Example #25
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show(self):
        if not self.drawn: self.draw()
        import pylab
        pylab.show() 
Example #26
Source File: plot.py    From TOPFARM with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_plot(self, filename):
        plt.ion()
        targarr = np.array(self.targvalue)
        self.posi[0].set_xdata(self.wt_positions[:,0])
        self.posi[0].set_ydata(self.wt_positions[:,1])
        while len(self.plotel)>0:
            self.plotel.pop(0).remove()
        self.plotel = self.shape_plot.plot(np.array([self.wt_positions[[i,j],0] for i, j in self.elnet_layout.keys()]).T,
                                   np.array([self.wt_positions[[i,j],1]  for i, j in self.elnet_layout.keys()]).T, 'y-', linewidth=1)
        for i in range(len(self.posb)):
            self.posb[i][0].set_xdata(self.iterations)
            self.posb[i][0].set_ydata(targarr[:,i])
            self.legend.texts[i].set_text('%s = %8.2f'%(self.targname[i], targarr[-1,i]))
        self.objf_plot.set_xlim([0, self.iterations[-1]])
        self.objf_plot.set_ylim([0.5, 1.2])
        if not self.title == '':
            plt.title('%s = %8.2f'%(self.title, getattr(self, self.title)))
        plt.draw()
        #print self.iterations[-1] , ': ' + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))])
        with open(self.result_file+'.results','a') as f:
            f.write( '%d:'%(self.inc) + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))]) +
                '\n')
        #plt.show()
        #plt.savefig(filename)
        display(plt.gcf())
        #plt.show()
        clear_output(wait=True) 
Example #27
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def smooth_line(line, smoothing=1, trim=True, draw=True):
    """

    This takes a line instance and smooths its data with nearest neighbor averaging.

    """

    # get the actual data values
    xdata = list(line.get_xdata())
    ydata = list(line.get_ydata())

    _fun.smooth_array(ydata, smoothing)

    if trim:
        for n in range(0, smoothing):
            xdata.pop(0); xdata.pop(-1)
            ydata.pop(0); ydata.pop(-1)

    # don't do anything if we don't have any data left
    if len(ydata) == 0:
        print("There's nothing left in "+str(line)+"!")
    else:
        # otherwise set the data with the new arrays
        line.set_data(xdata, ydata)

    # we refresh in real time for giggles
    if draw: _pylab.draw() 
Example #28
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_xticks(start, step, axes="gca"):
    """
    This will generate a tick array and apply said array to the axis
    """
    if axes=="gca": axes = _pylab.gca()

    # first get one of the tick label locations
    yposition = axes.xaxis.get_ticklabels()[0].get_position()[1]

    # get the bounds
    xmin, xmax = axes.get_xlim()

    # get the starting tick
    nstart = int(_pylab.floor((xmin-start)/step))
    nstop  = int(_pylab.ceil((xmax-start)/step))
    ticks = []
    for n in range(nstart,nstop+1): ticks.append(start+n*step)

    axes.set_xticks(ticks)

    # set the y-position
    for t in axes.xaxis.get_ticklabels():
        x, y = t.get_position()
        t.set_position((x, yposition))

    _pylab.draw() 
Example #29
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_yticks(start, step, axes="gca"):
    """
    This will generate a tick array and apply said array to the axis
    """
    if axes=="gca": axes = _pylab.gca()

    # first get one of the tick label locations
    xposition = axes.yaxis.get_ticklabels()[0].get_position()[0]

    # get the bounds
    ymin, ymax = axes.get_ylim()

    # get the starting tick
    nstart = int(_pylab.floor((ymin-start)/step))
    nstop  = int(_pylab.ceil((ymax-start)/step))
    ticks = []
    for n in range(nstart,nstop+1): ticks.append(start+n*step)

    axes.set_yticks(ticks)

    # set the x-position
    for t in axes.yaxis.get_ticklabels():
        x, y = t.get_position()
        t.set_position((xposition, y))

    _pylab.draw() 
Example #30
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_yrange(ymin="same", ymax="same", axes="gca"):
    if axes == "gca": axes = _pylab.gca()

    ylim = axes.get_ylim()

    if ymin == "same": ymin = ylim[0]
    if ymax == "same": ymax = ylim[1]

    axes.set_ylim(ymin,ymax)
    _pylab.draw()