Example #1
0
def correlationPlot(x,y,name=None,xlabel='PAR0',ylabel='PAR1',order=1,NptsStat=21,NptsPlotfit=500,usemad=True):
  p = np.polyfit(x,y,order)
  statedges = np.linspace(np.min(x),np.max(x),NptsStat)
  statbins = np.digitize(x,statedges)
  stato = np.zeros(NptsStat-1)
  for n in xrange(NptsStat-1):
    if usemad:
      stato[n]= toolsDistrAndHist.mad(y[n+1==statbins])
    else:
      stato[n]= np.std(y[n+1==statbins])

  statx = toolsDistrAndHist.histVecCenter(statedges)
  xf = np.linspace(np.min(x),np.max(x),NptsPlotfit)
  yf = np.polyval(p,xf)

  fig,axs = subplots(3,1,sharex=True,figname=name,figsize=(14,6),hspace=0)
  axs[0].plot(x,y,'.k',ms=2)
  axs[0].plot(xf,yf,'r-',lw=2)
  axs[0].errorbar(statx,np.polyval(p,statx),yerr=stato,fmt='r.',lw=2,capthick=2)
  axs[0].set_ylabel(ylabel)


  axs[1].plot(x,y-np.polyval(p,x),'.k',ms=2)
  axs[1].plot(xf,np.zeros_like(xf),'r',lw=2)
  axs[1].errorbar(statx,np.zeros_like(statx),yerr=stato,fmt='r.',lw=2,capthick=2)
  axs[1].set_ylabel('%s - $<$%s$>$'%(ylabel,ylabel))

  axs[2].step(statx,stato/np.polyval(np.polyder(p),statx),where='mid',color='k',lw=2)
  axs[2].axhline(0,color='r')
  axs[2].set_ylabel('$\sigma_{%s} / \\frac{d<%s>}{d%s}$'%(ylabel,ylabel,xlabel))
  axs[2].set_xlabel(xlabel)
  plt.draw_if_interactive()

  return p 
Example #2
0
    def add_overlay(self, img, threshold=1e-6, colorbar=False, **kwargs):
        """ Plot a 3D map in all the views.

            Parameters
            -----------
            img: Niimg-like object
                See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg.
                If it is a masked array, only the non-masked part will be
                plotted.
            threshold : a number, None
                If None is given, the maps are not thresholded.
                If a number is given, it is used to threshold the maps:
                values below the threshold (in absolute value) are
                plotted as transparent.
            colorbar: boolean, optional
                If True, display a colorbar on the right of the plots.
            kwargs:
                Extra keyword arguments are passed to imshow.
        """
        if colorbar and self._colorbar:
            raise ValueError("This figure already has an overlay with a " "colorbar.")
        else:
            self._colorbar = colorbar

        img = _utils.check_niimg_3d(img)

        # Make sure that add_overlay shows consistent default behavior
        # with plot_stat_map
        kwargs.setdefault("interpolation", "nearest")
        ims = self._map_show(img, type="imshow", threshold=threshold, **kwargs)

        if colorbar:
            self._colorbar_show(ims[0], threshold)

        plt.draw_if_interactive()
Example #3
0
    def _init_figure(self, **kwargs):
        from matplotlib import pyplot

        # add new attributes
        self.colorbars = []
        self._coloraxes = []

        # create Figure
        num = kwargs.pop('num', max(pyplot.get_fignums() or {0}) + 1)
        self._parse_subplotpars(kwargs)
        super(Plot, self).__init__(**kwargs)
        self.number = num

        # add interactivity (scraped from pyplot.figure())
        backend_mod = get_backend_mod()
        try:
            manager = backend_mod.new_figure_manager_given_figure(num, self)
        except AttributeError:
            upstream_mod = importlib.import_module(
                pyplot.new_figure_manager.__module__)
            canvas = upstream_mod.FigureCanvasBase(self)
            manager = upstream_mod.FigureManagerBase(canvas, 1)
        manager._cidgcf = manager.canvas.mpl_connect(
            'button_press_event',
            lambda ev: _pylab_helpers.Gcf.set_active(manager))
        _pylab_helpers.Gcf.set_active(manager)
        pyplot.draw_if_interactive()
Example #4
0
    def add_contours(self, img, filled=False, **kwargs):
        """ Contour a 3D map in all the views.

            Parameters
            -----------
            img: Niimg-like object
                See http://nilearn.github.io/manipulating_visualizing/manipulating_images.html#niimg.
                Provides image to plot.
            filled: boolean, optional
                If filled=True, contours are displayed with color fillings.
            kwargs:
                Extra keyword arguments are passed to contour, see the
                documentation of pylab.contour
                Useful, arguments are typical "levels", which is a
                list of values to use for plotting a contour, and
                "colors", which is one color or a list of colors for
                these contours.
        """
        self._map_show(img, type='contour', **kwargs)
        if filled:
            colors = kwargs['colors']
            levels = kwargs['levels']
            # contour fillings levels should be given as (lower, upper).
            levels.append(np.inf)
            alpha = kwargs['alpha']
            self._map_show(img, type='contourf', levels=levels, alpha=alpha,
                           colors=colors[:3])

        plt.draw_if_interactive()
Example #5
0
    def plot(self,axes=None,xlabel=True,ylabel=True,frameon=True,xticks=None,
             yticks=None,**kwargs):
        if axes==None:
            axes = gca()
        blend = kwargs.pop('blend',1)
        maxspikes = kwargs.pop('maxspikes',None)
        
        extents = [self.starttime_float,self.endtime_float,
                   self.n_trials+.5,.5]
        im = axes.imshow(repeat(self.data,blend,axis=0),
                         aspect='auto', cmap=cm.bone_r,
                         interpolation='bilinear',extent=extents,
                         origin='upper')
        axes.yaxis.set_major_locator(MultipleLocator(1))
        
        if maxspikes is not None:
            im.set_clim([0,maxspikes])
            
        if xlabel:
            axes.set_xlabel('Time [s]')
        if ylabel:
            axes.set_ylabel('Trial')
        
        axes.set_frame_on(frameon)
        
        if xticks is not None:
            axes.set_xticks(xticks)

        if yticks is not None:
            axes.set_yticks(yticks)
            
        draw_if_interactive()
        return axes
Example #6
0
    def _draw_span(self):
        if not (self._ax and self.op.low and self.op.high):
            return
        
        if self._low_line and self._low_line in self._ax.lines:
            self._low_line.remove()
        
        if self._high_line and self._high_line in self._ax.lines:
            self._high_line.remove()
            
        if self._hline and self._hline in self._ax.lines:
            self._hline.remove()
            

        self._low_line = plt.axvline(self.op.low, linewidth=3, color='blue')
        self._high_line = plt.axvline(self.op.high, linewidth=3, color='blue')
            
        ymin, ymax = plt.ylim()
        y = (ymin + ymax) / 2.0
        self._hline = plt.plot([self.op.low, self.op.high], 
                               [y, y], 
                               color='blue', 
                               linewidth = 2)[0]
                                   
        plt.draw_if_interactive()
Example #7
0
    def Fct_RangeX(self,x=None,f=1.0):
        '''
xrange=RangeX(x=None,f=1.0)
    If x is given then it is treated as a range with a min and
    max value. The x-limits of the active plot are set to this range multiplied
    by f. If f is a list of two values then f[0] is used for the lower limit and
    f[1] is used for the upper limit.
    The function returns the x-range of the active plot.
'''
        ax=plt.gca()
        ch=False
        f1=f2=f
        if not isFloat(f):
            f1=f[0]
            f2=f[1]
        if not (x is None):
            xi=min(x)
            xa=max(x)
            xm=(xa+xi)/2
            xi=f1*(xi-xm)+xm
            xa=f2*(xa-xm)+xm
            ax.set_xlim(xi,xa)
            ch=True
        if ch: 
            plt.draw_if_interactive()
        return ax.get_xlim()
Example #8
0
    def Fct_RangeY(self,y=None,f=1.0):
        '''
yrange=RangeY(y=None,f=1.0)
    If y is given then it is treated as a range with a min and
    max value. The y-limits of the active plot are set to this range multiplied
    by f. If f is a list of two values then f[0] is used for the lower limit and
    f[1] is used for the upper limit.
    The function returns the y-range of the active plot.
'''
        ax=plt.gca()
        ch=False
        f1=f2=f
        if not isFloat(f):
            f1=f[0]
            f2=f[1]
        if not (y is None):
            yi=min(y)
            ya=max(y)
            ym=(ya+yi)/2
            yi=f1*(yi-ym)+ym
            ya=f2*(ya-ym)+ym
            ax=plt.gca()
            ax.set_ylim(yi,ya)
            ch=True
        if ch: 
            plt.draw_if_interactive()
        return ax.get_ylim()
Example #9
0
    def Fct_Range(self,x=None,y=None,f=1.0):
        '''
xrange,yrange=Range(x=None,y=None,f=1.0)
    If x or y are given then they are treated as a range with a min and
    max value. The limits of the active plot are set to these ranges multiplied
    by f. If f is a list of two values then f[0] is used for the lower limit and
    f[1] is used for the upper limit.
    The function returns the x- and y-range of the active plot.
'''
        ax=plt.gca()
        ch=False
        f1=f2=f
        if not isFloat(f):
            f1=f[0]
            f2=f[1]
        if not (x is None):
            xi=min(x)
            xa=max(x)
            xm=(xa+xi)/2
            xi=1.*f1*(xi-xm)+xm
            xa=1.*f2*(xa-xm)+xm
            ax.set_xlim(xi,xa)
            ch=True
        if not (y is None):
            yi=min(y)
            ya=max(y)
            ym=(ya+yi)/2
            yi=f1*(yi-ym)+ym
            ya=f2*(ya-ym)+ym
            ax.set_ylim(yi,ya)
            ch=True
        if ch: 
            plt.draw_if_interactive()
        return (ax.get_xlim(),ax.get_ylim())
Example #10
0
    def add_edges(self, img, color='r'):
        """ Plot the edges of a 3D map in all the views.

            Parameters
            -----------
            map: 3D ndarray
                The 3D map to be plotted. If it is a masked array, only
                the non-masked part will be plotted.
            affine: 4x4 ndarray
                The affine matrix giving the transformation from voxel
                indices to world space.
            color: matplotlib color: string or (r, g, b) value
                The color used to display the edge map
        """
        img = reorder_img(img)
        data = img.get_data()
        affine = img.get_affine()
        single_color_cmap = colors.ListedColormap([color])
        data_bounds = get_bounds(data.shape, img.get_affine())

        # For each ax, cut the data and plot it
        for display_ax in self.axes.values():
            try:
                data_2d = display_ax.transform_to_2d(data, affine)
                edge_mask = _edge_map(data_2d)
            except IndexError:
                # We are cutting outside the indices of the data
                continue
            display_ax.draw_2d(edge_mask, data_bounds, data_bounds,
                               type='imshow', cmap=single_color_cmap)

        plt.draw_if_interactive()
Example #11
0
    def plot_forecast(self, steps=1, figsize=(10, 10)):
        """
        Plot h-step ahead forecasts against actual realizations of time
        series. Note that forecasts are lined up with their respective
        realizations.

        Parameters
        ----------
        steps :
        """
        fig, axes = plt.subplots(figsize=figsize, nrows=self.neqs,
                                 sharex=True)

        forc = self.forecast(steps=steps)
        dates = forc.index

        y_overlay = self.y.reindex(dates)

        for i, col in enumerate(forc.columns):
            ax = axes[i]

            y_ts = y_overlay[col]
            forc_ts = forc[col]

            y_handle = ax.plot(dates, y_ts.values, 'k.', ms=2)
            forc_handle = ax.plot(dates, forc_ts.values, 'k-')

        fig.legend((y_handle, forc_handle), ('Y', 'Forecast'))
        fig.autofmt_xdate()

        fig.suptitle('Dynamic %d-step forecast' % steps)

        # pretty things up a bit
        plotting.adjust_subplots(bottom=0.15, left=0.10)
        plt.draw_if_interactive()
Example #12
0
def csplot(series, *args, **kwargs):
    """
    Plots the series to the current :class:`ClimateSeriesPlot` subplot.
    If the current plot is not a :class:`ClimateSeriesPlot`, 
    a new :class:`ClimateFigure` is created.

    """
    # allow callers to override the hold state by passing hold=True|False
    b = pyplot.ishold()
    h = kwargs.pop('hold', None)
    if h is not None:
        pyplot.hold(h)
    # Get the current figure, or create one
    figManager = _pylab_helpers.Gcf.get_active()
    if figManager is not None :
        fig = figManager.canvas.figure
        if not isinstance(fig, ClimateFigure):
            fig = csfigure(series=series)
    else:
        fig = csfigure(series=series)
    # Get the current axe, or create one
    sub = fig._axstack()
    if sub is None:
        sub = fig.add_csplot(111, series=series, **kwargs)
    try:
        ret = sub.csplot(series, *args, **kwargs)
        pyplot.draw_if_interactive()
    except:
        pyplot.hold(b)
        raise
    pyplot.hold(b)
    return ret
Example #13
0
def legend(*args, **kwargs):
    """
    Overwrites the pylab legend function.

    It adds another location identifier 'outer right'
    which locates the legend on the right side of the plot

    The args and kwargs are forwarded to the pylab legend function
    """
    if kwargs.has_key('loc'):
        loc = kwargs['loc']
        if (loc == 'outer'):
            global new
            kwargs.pop('loc')
            leg = plt.legend(loc=(0,0), *args, **kwargs)
            frame = leg.get_frame()
            currentAxes = plt.gca()
            barray = currentAxes.get_position().get_points()
            currentAxesPos = [barray[0][0], barray[0][1], barray[1][0], barray[1][1]]
            currentAxes.set_position([currentAxesPos[0]-0.02, currentAxesPos[1], currentAxesPos[2] - 0.2, currentAxesPos[3]-currentAxesPos[1]])
            version = mpl.__version__.split(".")
            #if map(int, version) < [0, 98]:
            #   leg._loc = (1 + leg.axespad, 0.0)
            #else:
            leg._loc = (1.03, -0.05) # + leg.borderaxespad, 0.0)
            plt.draw_if_interactive()
            return leg
    return plt.legend(*args, **kwargs)
Example #14
0
 def drawFigure(self, title=None, **kw):
     """Draw the figure.  
     Extra arguments are forwarded to self.makeFigure()"""
     import matplotlib.pyplot as plt
     fig = self.makeFigure(**kw)
     if title is not None:
         fig.suptitle(title)
     plt.draw_if_interactive()
Example #15
0
 def onscroll(event):
     if event.button == "up":
         for origline, legline in lined2.items():
             toggle_visibility(origline, legline, True)
     elif event.button == "down":
         for origline, legline in lined2.items():
             toggle_visibility(origline, legline, False)
     pyplot.draw_if_interactive()
Example #16
0
def pltfactcamera(*args, **kwargs):
    ax = plt.gca()
    fig = ax.get_figure()
    fig.canvas.mpl_connect("pick_event", onpick)
    ret = ax.factcamera(*args, **kwargs)
    plt.draw_if_interactive()
    plt.sci(ret)
    return ret
def host_subplot(*args, **kwargs):
    import matplotlib.pyplot as plt
    axes_class = kwargs.pop("axes_class", None)
    host_subplot_class = host_subplot_class_factory(axes_class)
    fig = plt.gcf()
    ax = host_subplot_class(fig, *args, **kwargs)
    fig.add_subplot(ax)
    plt.draw_if_interactive()
    return ax
Example #18
0
def clim_std(stdfac=1,ih=None):
  if not ih:
    ih = plt.gci()
  #ihandles = h.findobj(matplotlib.image.AxesImage)
  #ih = ihandles[-1]
  im = ih.get_array()
  imean = np.median(im.ravel()[~np.isnan(im.ravel())])
  istd = mad(im.ravel()[~np.isnan(im.ravel())])
  ih.set_clim([imean-stdfac*istd,imean+stdfac*istd])
  plt.draw_if_interactive()
Example #19
0
def align_ylabels(axs):
  "doesn't work yet!!"
  x,y = zip(*(ax.yaxis.label.get_position() for ax in axs))
  print(x,y)
  xmn = min(x)
  print(xmn)
  for ax,ty in zip(axs,y):
    ax.yaxis.label.set_position((xmn,ty))
    print(ax.yaxis.label.get_position())
    ax.yaxis.label.update_bbox_position_size()
  plt.draw_if_interactive()
Example #20
0
    def plot_vs_temperature(self, **kwargs):
        import matplotlib.pyplot as plt
        ax = kwargs.pop('ax', plt.gca())

        lines = ax.loglog(self.temperature, self.y.T, **kwargs)
        ax.set_xlabel('$T_\mathrm{e}\ [\mathrm{eV}]$')
        ax.set_ylim(0.05, 1.3)
        self.annotate_ionisation_stages(lines)
        plt.draw_if_interactive()

        return lines
Example #21
0
    def draw_circle(self, xd, yd, label, plot_kwargs):
        """Draw a red or blue circle"""
        # Destory old
        self.destroy_handle(label)
        
        # Draw it
        obj, = self.ax.plot(xd, yd, marker='o', **plot_kwargs)
        plt.draw_if_interactive()

        # Keep a record
        self.handles_d[label] = obj
        return obj
Example #22
0
    def plot(self, label=None, kind='line', use_index=True, rot=30, ax=None,
             style='-', **kwds): # pragma: no cover
        """
        Plot the input series with the index on the x-axis using
        matplotlib / pylab.

        Parameters
        ----------
        label : label argument to provide to plot
        kind : {'line', 'bar', 'hist'}
            Default: line for TimeSeries, hist for Series
        auto_x : if True, it will use range(len(self)) as x-axis
        kwds : other plotting keyword arguments

        Notes
        -----
        See matplotlib documentation online for more on this subject

        Default plot-types: TimeSeries (line), Series (bar)

        Intended to be used in ipython -pylab mode
        """
        import matplotlib.pyplot as plt

        if label is not None:
            kwds = kwds.copy()
            kwds['label'] = label

        N = len(self)

        if ax is None:
            ax = plt.gca()

        if kind == 'line':
            if use_index:
                x = self.index
            else:
                x = range(len(self))

            ax.plot(x, self.values, style, **kwds)
        elif kind == 'bar':
            xinds = np.arange(N) + 0.25
            ax.bar(xinds, self.values, 0.5, bottom=np.zeros(N), linewidth=1)

            if N < 10:
                fontsize = 12
            else:
                fontsize = 10

            ax.set_xticks(xinds + 0.25)
            ax.set_xticklabels(self.index, rotation=rot, fontsize=fontsize)

        plt.draw_if_interactive()
Example #23
0
def smooth_contourf(*args,**kwargs):
    kwargs['filled'] = True
    ax=kwargs.pop('ax',pyp.gca())
    washold = ax.ishold()
    hold = kwargs.pop('hold', None)
    if hold is not None:
        ax.hold(hold)
    try:
        ret = SmoothContour(ax,*args,**kwargs)
        pyp.draw_if_interactive()
    finally:
        ax.hold(washold)
    if ret._A is not None: pyp.sci(ret)
    return ret 
Example #24
0
 def _draw_rect(self):
     if not self._ax:
         return
     
     if self._box and self._box in self._ax.patches:
         self._box.remove()
         
     if self.op.xlow and self.op.xhigh and self.op.ylow and self.op.yhigh:
         self._box = Rectangle((self.op.xlow, self.op.ylow), 
                               (self.op.xhigh - self.op.xlow), 
                               (self.op.yhigh - self.op.ylow), 
                               facecolor="grey",
                               alpha = 0.2)
         self._ax.add_patch(self._box)
         plt.draw_if_interactive()
Example #25
0
 def plot(self,axes=None,max_rate=None,**kwargs):
     if axes==None:
         axes = gca()
     times = to_float(self.time)
     axes.hold(False)
     
     # Get axis keywords
     axes_kwargs, kwargs = parse_keywords(kwargs,['axis'])
     
     '''
     Allow xlabel ylabel, xticks, yticks to be the same as axes_xlabel etc.
     axes_ etc. take precedence.
     '''
     xlabel = kwargs.pop('xlabel',True)
     xlabel = 'Time [s]' if xlabel is True \
                         else '' if xlabel is False \
                         else xlabel
     axes_kwargs.setdefault('xlabel',xlabel)
     
     ylabel = kwargs.pop('ylabel',True)
     ylabel = 'Rate [spikes/s]' if ylabel is True \
                                else '' if ylabel is False \
                                else ylabel
     axes_kwargs.setdefault('ylabel',ylabel)
     
     xticks = kwargs.pop('xticks',True)
     if xticks is not True:
         axes_kwargs['xticks'] = xticks
         
     yticks = kwargs.pop('yticks',True)
     if yticks is not True:
         axes_kwargs['yticks'] = yticks
     
     # Plot the PSTH line
     axes.plot(times,self.t_rate*self.data,**kwargs)
     
     # Set tight limits on axis
     axes_kwargs['xlim'] = [self.starttime_float,self.endtime_float]
     
     # Set limit on y axis
     if max_rate is not None:
         axes_kwargs['ylim'] = [0,max_rate]
     
     # Set all axis properties
     setp(axes,**axes_kwargs)
         
     draw_if_interactive()
     return axes
Example #26
0
    def Cmd_UpdatePlot(self):
        '''
UpdatePlot()
    Updates the active plot after changes in the plotting parameters. 
'''
        plt.title(VarConv(self.opts,self.Prp_PlotParams,self.Prp_PlotParams['Title']),fontsize=self.opts['-tls'],x=0.5,y=1.01)
        ax=plt.gca()
        ax.set_xlabel(VarConv(self.opts,self.Prp_PlotParams,VarConv(self.opts,self.Prp_PlotParams,self.Prp_PlotParams['Xlabel'])),size=self.opts['-xls'])
        ax.set_ylabel(VarConv(self.opts,self.Prp_PlotParams,VarConv(self.opts,self.Prp_PlotParams,self.Prp_PlotParams['Ylabel'])),size=self.opts['-yls'])
        for tick in ax.xaxis.get_major_ticks():
            tick.label1.set_fontsize(self.opts['-xts'])
        for tick in ax.yaxis.get_major_ticks():
            tick.label1.set_fontsize(self.opts['-yts'])
        plt.grid(False)
        plt.draw_if_interactive()
        return
Example #27
0
def lines(xy, c='b', vmin=None, vmax=None, **kwargs):
    """
    xy : sequence of array 
        Coordinates of points in lines.
        `xy` is a sequence of array (line0, line1, ..., lineN) where
            line = [(x0, y0), (x1, y1), ... (xm, ym)]
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)
        `c` can be a 2-D array in which the rows are RGB or RGBA, however.
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, linewidth(lw), linestyle(ls), norm, cmap, transform, etc.

    Returns
    -------
    collection : `~matplotlib.collections.LineCollection`
    """
    if np.isscalar(c):
        kwargs.setdefault('color', c)
        c = None

    if 'ls' in kwargs:
        kwargs.setdefault('linestyle', kwargs.pop('ls'))
    if 'lw' in kwargs:
        kwargs.setdefault('linewidth', kwargs.pop('lw'))

    collection = LineCollection(xy, **kwargs)
    if c is not None:
        collection.set_array(np.asarray(c))
        collection.set_clim(vmin, vmax)

    ax = plt.gca()
    ax.add_collection(collection)
    ax.autoscale_view()
    plt.draw_if_interactive()
    if c is not None:
        plt.sci(collection)
    return collection
Example #28
0
    def Fct_Histogram(self,data,normed=True,range=None):
        '''
bin_limits,bin_heights = Histogram(data,normed=True,range=None)
    Plots the given data as a histogram. By default (normed=True)
    the heights will be normed (pdf-sample) and the full range of
    the data will be used.
    The function returns the bin limits and the bin heights as 
    arrays of length len(data)+1.  
'''
        # the histogram of the data
        nob=self.Prp_PlotParams['Bars']
        color=self.Prp_PlotParams['Color']
        alpha=self.Prp_PlotParams['Alpha']
        n, bins, patches = plt.gca().hist(data, nob,range=range, normed=normed, facecolor=color, edgecolor=color, alpha=alpha)
        n1=np.hstack((n,np.zeros(1)))
        plt.draw_if_interactive()
        return bins,n1
Example #29
0
	def wrapper(*args, **kwargs):
		try:
			isInteractive = plt.isinteractive()

			# switch to non-interactive mode
			#matplotlib.interactive(False)

			ret = func(*args, **kwargs)

			matplotlib.interactive(isInteractive)

			draw_if_interactive()
			return ret
		except Exception as exc:
			# switch back
			matplotlib.interactive(isInteractive)
			raise
Example #30
0
    def update_image(self, arr, title=''):
        """Draw a new image"""
        self.destroy_all_handles()
        
        # Display
        im = my.plot.imshow(arr, cmap=plt.cm.gray, ax=self.ax)
        self.handles_d['image'] = im
        self.ax.set_title(title)

        # Zoom
        self.ax.set_xlim((160, 320))
        self.ax.set_ylim((120, 0))
        
        # Trim
        my.plot.harmonize_clim_in_subplots(fig=self.f, 
            trim=trim_trans(self.trim))

        plt.draw_if_interactive()
def host_axes(*args, axes_class=None, figure=None, **kwargs):
    """
    Create axes that can act as a hosts to parasitic axes.

    Parameters
    ----------
    figure : `matplotlib.figure.Figure`
        Figure to which the axes will be added. Defaults to the current figure
        `pyplot.gcf()`.

    *args, **kwargs
        Will be passed on to the underlying ``Axes`` object creation.
    """
    import matplotlib.pyplot as plt
    host_axes_class = host_axes_class_factory(axes_class)
    if figure is None:
        figure = plt.gcf()
    ax = host_axes_class(figure, *args, **kwargs)
    figure.add_axes(ax)
    plt.draw_if_interactive()
    return ax
Example #32
0
    def _draw_threshold(self):
        if not self._ax or not self.op.threshold:
            return

        if self._line:
            # when used in the GUI, _draw_threshold gets called *twice* without
            # the plot being updated inbetween: and then the line can't be
            # removed from the plot, because it was never added.  so check
            # explicitly first.  this is likely to be an issue in other
            # interactive plots, too.
            if self._line and self._line in self._ax.lines:
                self._line.remove()

            self._line = None

        if self.op.threshold:
            self._line = plt.axvline(self.op.threshold,
                                     linewidth=3,
                                     color='blue')

        plt.draw_if_interactive()
Example #33
0
def draw_specgram(x,
                  NFFT=256,
                  Fs=2,
                  Fc=0,
                  detrend=mlab.detrend_none,
                  window=mlab.window_hanning,
                  noverlap=128,
                  cmap=None,
                  xextent=None,
                  pad_to=None,
                  sides='default',
                  scale_by_freq=None,
                  hold=None,
                  **kwargs):
    ax = pyplot.gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = specgram1(x,
                        NFFT=NFFT,
                        Fs=Fs,
                        Fc=Fc,
                        detrend=detrend,
                        window=window,
                        noverlap=noverlap,
                        cmap=cmap,
                        xextent=xextent,
                        pad_to=pad_to,
                        sides=sides,
                        scale_by_freq=scale_by_freq,
                        **kwargs)

        pyplot.draw_if_interactive()
    finally:
        ax.hold(washold)
    pyplot.sci(ret[-1])
    return ret
Example #34
0
    def plot_objectives(self, ax=None, **kwargs):
        """
        Plots the collected objective values at each iteration.

        Parameters
        ----------
        ax : Axes
            Optional axes argument. If not passed, a new figure and axes are
            constructed.
        kwargs : dict
            Optional arguments passed to ``ax.plot``.
        """
        if ax is None:
            _, ax = plt.subplots()

        ax.plot(self.statistics.objectives, **kwargs)

        ax.set_title("Objective value at each iteration")
        ax.set_ylabel("Objective value")
        ax.set_xlabel("Iteration (#)")

        plt.draw_if_interactive()
Example #35
0
    def _draw_poly(self):
        if not self._ax:
            return

        if self._patch and self._patch in self._ax.patches:
            self._patch.remove()

        if self._drawing or not self.op.vertices or len(self.op.vertices) < 3 \
                         or any([len(x) != 2 for x in self.op.vertices]):
            return

        patch_vert = np.concatenate(
            (np.array(self.op.vertices), np.array((0, 0), ndmin=2)))

        self._patch = \
            mpl.patches.PathPatch(mpl.path.Path(patch_vert, closed = True),
                                  edgecolor="black",
                                  linewidth = 1.5,
                                  fill = False)

        self._ax.add_patch(self._patch)
        plt.draw_if_interactive()
Example #36
0
    def plot_forecast(self, steps=1, figsize=(10, 10)):
        """
        Plot h-step ahead forecasts against actual realizations of time
        series. Note that forecasts are lined up with their respective
        realizations.

        Parameters
        ----------
        steps :
        """
        import matplotlib.pyplot as plt

        fig, axes = plt.subplots(figsize=figsize, nrows=self.neqs,
                                 sharex=True)

        forc = self.forecast(steps=steps)
        dates = forc.index

        y_overlay = self.y.reindex(dates)

        for i, col in enumerate(forc.columns):
            ax = axes[i]

            y_ts = y_overlay[col]
            forc_ts = forc[col]

            y_handle = ax.plot(dates, y_ts.values, 'k.', ms=2)
            forc_handle = ax.plot(dates, forc_ts.values, 'k-')

        lines = (y_handle[0], forc_handle[0])
        labels =  ('Y', 'Forecast')
        fig.legend(lines,labels)
        fig.autofmt_xdate()

        fig.suptitle('Dynamic %d-step forecast' % steps)

        # pretty things up a bit
        plotting.adjust_subplots(bottom=0.15, left=0.10)
        plt.draw_if_interactive()
Example #37
0
    def _onclick(self, event):
        """Update selection traits"""
        if not self._ax:
            return

        if (self._cursor.ignore(event)):
            return

        # we have to check the wall clock time because the IPython notebook
        # doesn't seem to register double-clicks
        if event.dblclick or (time.clock() - self._last_click_time < 0.5):
            self._drawing = False
            self.op.vertices = map(tuple, self._path.vertices)
            self.op._xscale = plt.gca().get_xscale()
            self.op._yscale = plt.gca().get_yscale()
            self._path = None
            return

        self._last_click_time = time.clock()

        self._drawing = True
        if self._patch and self._patch in self._ax.patches:
            self._patch.remove()

        if self._path:
            vertices = np.concatenate((self._path.vertices,
                                       np.array((event.xdata, event.ydata),
                                                ndmin=2)))
        else:
            vertices = np.array((event.xdata, event.ydata), ndmin=2)

        self._path = mpl.path.Path(vertices, closed=False)
        self._patch = mpl.patches.PathPatch(self._path,
                                            edgecolor="black",
                                            fill=False)

        self._ax.add_patch(self._patch)
        plt.draw_if_interactive()
Example #38
0
    def _draw_span(self):
        if not (self._ax and self.op.low and self.op.high):
            return

        if self._low_line and self._low_line in self._ax.lines:
            self._low_line.remove()

        if self._high_line and self._high_line in self._ax.lines:
            self._high_line.remove()

        if self._hline and self._hline in self._ax.lines:
            self._hline.remove()

        self._low_line = plt.axvline(self.op.low, linewidth=3, color='blue')
        self._high_line = plt.axvline(self.op.high, linewidth=3, color='blue')

        ymin, ymax = plt.ylim()
        y = (ymin + ymax) / 2.0
        self._hline = plt.plot([self.op.low, self.op.high], [y, y],
                               color='blue',
                               linewidth=2)[0]

        plt.draw_if_interactive()
Example #39
0
def host_subplot(*args, **kwargs):
    """
    Create a subplot that can act as a host to parasitic axes.

    Parameters
    ----------
    figure : `matplotlib.figure.Figure`
        Figure to which the subplot will be added. Defaults to the current
        figure `pyplot.gcf()`.

    *args, **kwargs :
        Will be passed on to the underlying ``Axes`` object creation.
    """
    import matplotlib.pyplot as plt
    axes_class = kwargs.pop("axes_class", None)
    host_subplot_class = host_subplot_class_factory(axes_class)
    fig = kwargs.get("figure", None)
    if fig is None:
        fig = plt.gcf()
    ax = host_subplot_class(fig, *args, **kwargs)
    fig.add_subplot(ax)
    plt.draw_if_interactive()
    return ax
Example #40
0
def draw_graph(graph: Graph,
               pos: dict = None,
               nodes_list: list = None,
               nodes_size: Union[int, list] = 50,
               nodes_color: Union[str, list] = 'r',
               edges_list: list = None,
               edges_color: Union[str, list] = 'k',
               axes: plt.Axes = None) -> None:
    """
    Draw graph using matplotlib.

    :param graph: graph
    :param pos: node -> position (x,y) dictionary
    :param nodes_list: nodes to draw
    :param nodes_size: nodes size, scalar or sequence
    :param nodes_color: nodes color, scalar or sequence (matplotlib compatible)
    :param edges_list: edges to draw
    :param edges_color: nodes color, scalar or sequence (matplotlib compatible)
    :param axes: axes to draw the graph at
    """
    draw_nodes(graph, pos, nodes_list, nodes_size, nodes_color, axes)
    draw_edges(graph, pos, edges_list, edges_color, axes)
    plt.draw_if_interactive()
Example #41
0
def simpplot(p, t, *args, **kwargs):
    """Plot a simplicial mesh

    Parameters
    ----------
    p : array, shape (np, dim)
        nodes
    t : array, shape (nt, dim+1)
        elements

    Additional 2D parameters
    ------------------------
    nodes : bool, optional
        draw a marker at each node
    annotate : str, optional
        'p' : annotate nodes
        't' : annotate simplices

    Additional 3D parameters
    ------------------------
    pmask : callable or bool array of shape (np,)
    """
    ax = plt.gca()
    try:
        dim = p.shape[1]
        if dim == 2:
            ret = axes_simpplot2d(ax, p, t, *args, **kwargs)
        elif dim == 3:
            import mpl_toolkits.mplot3d
            ax = plt.gca(projection='3d')
            ret = axes_simpplot3d(ax, p, t, *args, **kwargs)
        else:
            raise NotImplementedError("Unknown dimension.")
        plt.draw_if_interactive()
    finally:
        pass
    return ret
Example #42
0
    def plot(self, **kwargs):
        import matplotlib.pyplot as plt
        if 'x' in kwargs:
            xscale = 'linear'
        else:
            xscale = 'log'

        ax = kwargs.get('ax', plt.gca())
        x = kwargs.get('x', self.temperature)

        lines = []
        for key in ['line_power', 'continuum_power', 'cx_power', 'total']:
            p = self.specific_power[key]
            l, = ax.semilogy(x, p, label=self._get_label(key))
            lines.append(l)

        ax.set_xscale(xscale)
        ax.set_xlabel(r'$T_\mathrm{e}\ [\mathrm{eV}]$')
        ax.set_ylabel(r'$P\ [\mathrm{W/m^3}]$')

        self._decorate_plot(ax, lines)
        plt.draw_if_interactive()

        return lines
Example #43
0
def boxplot_frame(self,
                  column=None,
                  by=None,
                  ax=None,
                  fontsize=None,
                  rot=0,
                  grid=True,
                  figsize=None,
                  layout=None,
                  return_type=None,
                  **kwds):
    ax = boxplot(self,
                 column=column,
                 by=by,
                 ax=ax,
                 fontsize=fontsize,
                 grid=grid,
                 rot=rot,
                 figsize=figsize,
                 layout=layout,
                 return_type=return_type,
                 **kwds)
    plt.draw_if_interactive()
    return ax
Example #44
0
def plot_coherence(tar,
                   est,
                   fs=fs_d,
                   tfft=tfft_d,
                   logy=False,
                   save=False,
                   title=None):
    if title is None:
        title = 'Coherence of Target with Estimate'

    nperseg = fs * tfft

    ff, C = sig.coherence(tar, est, fs=fs, nperseg=nperseg)

    fig, ax = plt.subplots()

    ax.plot(ff, C, label='Coherence with Estimate')

    ax.set_xscale('log')
    ax.set_xlim([10, fs // 2])
    if logy:
        ax.set_yscale('log')
        ax.set_ylim([1e-3, 1.05])
    else:
        ax.set_ylim([0, 1.05])

    ax.set_xlabel('Freq [Hz]')
    ax.set_ylabel('Coherence')
    ax.set_title(title)

    if save:
        _save_incremented(fig, 'coherence')
    else:
        plt.draw_if_interactive()

    return fig, ax
Example #45
0
    def add_overlay(self, img, threshold=1e-6, colorbar=False, **kwargs):
        """ Plot a 3D map in all the views.

            Parameters
            -----------
            img: Niimg-like object
                See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg.
                If it is a masked array, only the non-masked part will be
                plotted.
            threshold : a number, None
                If None is given, the maps are not thresholded.
                If a number is given, it is used to threshold the maps:
                values below the threshold (in absolute value) are
                plotted as transparent.
            colorbar: boolean, optional
                If True, display a colorbar on the right of the plots.
            kwargs:
                Extra keyword arguments are passed to imshow.
        """
        if colorbar and self._colorbar:
            raise ValueError("This figure already has an overlay with a "
                             "colorbar.")
        else:
            self._colorbar = colorbar

        img = _utils.check_niimg_3d(img)

        # Make sure that add_overlay shows consistent default behavior
        # with plot_stat_map
        kwargs.setdefault('interpolation', 'nearest')
        ims = self._map_show(img, type='imshow', threshold=threshold, **kwargs)

        if colorbar:
            self._colorbar_show(ims[0], threshold)

        plt.draw_if_interactive()
Example #46
0
        
        entropy_here = l_function(E)
        plt.clf()
        if 'erfinv' in base:
            plt.plot(E, entropy_here, label=f)
            plt.plot(E, exact_entropy, '--', label='exact')
            plt.ylabel('$S(E)$')
        else:
            plt.plot(E, np.exp(entropy_here), label=f)
            plt.plot(E, np.exp(exact_entropy), '--', label='exact')
            plt.ylabel('density of states')
        plt.xlabel('E')
        # plt.ylim(bottom=0)
        plt.legend(loc='best')
        plt.show()'''
        plt.draw_if_interactive()
        plt.pause(0.1)
        max_error = np.max(np.abs(entropy_here - exact_entropy))
        error[base].append(max_error)
        #FIXME: the error is off by factor of 2

#Plotting
plt.figure()
for base in bases:
    plt.loglog(moves[base], error[base], label=str(base))

plt.xlabel('Moves')
plt.ylabel('Error (S - S$_{exact}$)')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
Example #47
0
def mpl_draw(graph, pos=None, ax=None, arrows=True, with_labels=False, **kwds):
    r"""Draw a graph with Matplotlib.

    .. note::

        Matplotlib is an optional dependency and will not be installed with
        retworkx by default. If you intend to use this function make sure that
        you install matplotlib with either ``pip install matplotlib`` or
        ``pip install 'retworkx[mpl]'``

    :param graph: A retworkx graph, either a :class:`~retworkx.PyGraph` or a
        :class:`~retworkx.PyDiGraph`.
    :param dict pos: An optional dictionary (or
        a :class:`~retworkx.Pos2DMapping` object) with nodes as keys and
        positions as values. If not specified a spring layout positioning will
        be computed. See `layout_functions` for functions that compute
        node positions.
    :param matplotlib.Axes ax: An optional Matplotlib Axes object to draw the
        graph in.
    :param bool arrows: For :class:`~retworkx.PyDiGraph` objects if ``True``
        draw arrowheads. (defaults to ``True``) Note, that the Arrows will
        be the same color as edges.
    :param str arrowstyle: An optional string for directed graphs to choose
        the style of the arrowsheads. See
        :class:`matplotlib.patches.ArrowStyle` for more options. By default the
        value is set to ``'-\|>'``.
    :param int arrow_size: For directed graphs, choose the size of the arrow
        head's length and width. See
        :class:`matplotlib.patches.FancyArrowPatch` attribute and constructor
        kwarg ``mutation_scale`` for more info. Defaults to 10.
    :param bool with_labels: Set to ``True`` to draw labels on the nodes. Edge
        labels will only be drawn if the ``edge_labels`` parameter is set to a
        function. Defaults to ``False``.
    :param list node_list: An optional list of node indices in the graph to
        draw. If not specified all nodes will be drawn.
    :param list edge_list: An option list of edges in the graph to draw. If not
        specified all edges will be drawn
    :param int|list node_size: Optional size of nodes. If an array is
        specified it must be the same length as node_list. Defaults to 300
    :param node_color: Optional node color. Can be a single color or
        a sequence of colors with the same length as node_list. Color can be
        string or rgb (or rgba) tuple of floats from 0-1. If numeric values
        are specified they will be mapped to colors using the ``cmap`` and
        ``vmin``,``vmax`` parameters. See :func:`matplotlib.scatter` for more
        details. Defaults to ``'#1f78b4'``)
    :param str node_shape: The optional shape node. The specification is the
        same as the :func:`matplotlib.pyplot.scatter` function's ``marker``
        kwarg, valid options are one of
        ``['s', 'o', '^', '>', 'v', '<', 'd', 'p', 'h', '8']``. Defaults to
        ``'o'``
    :param float alpha: Optional value for node and edge transparency
    :param matplotlib.colors.Colormap cmap: An optional Matplotlib colormap
        object for mapping intensities of nodes
    :param float vmin: Optional minimum value for node colormap scaling
    :param float vmax: Optional minimum value for node colormap scaling
    :param float|sequence linewidths: An optional line width for symbol
        borders. If a sequence is specified it must be the same length as
        node_list. Defaults to 1.0
    :param float|sequence width: An optional width to use for edges. Can
        either be a float or sequence  of floats. If a sequence is specified
        it must be the same length as node_list. Defaults to 1.0
    :param str|sequence edge_color: color or array of colors (default='k')
        Edge color. Can be a single color or a sequence of colors with the same
        length as edge_list. Color can be string or rgb (or rgba) tuple of
        floats from 0-1. If numeric values are specified they will be
        mapped to colors using the ``edge_cmap`` and ``edge_vmin``,
        ``edge_vmax`` parameters.
    :param matplotlib.colors.Colormap edge_cmap: An optional Matplotlib
        colormap for mapping intensities of edges.
    :param float edge_vmin: Optional minimum value for edge colormap scaling
    :param float edge_vmax: Optional maximum value for node colormap scaling
    :param str style: An optional string to specify the edge line style.
        For example, ``'-'``, ``'--'``, ``'-.'``, ``':'`` or words like
        ``'solid'`` or ``'dashed'``. See the
        :class:`matplotlib.patches.FancyArrowPatch` attribute and kwarg
        ``linestyle`` for more details. Defaults to ``'solid'``.
    :param func labels: An optional callback function that will be passed a
        node payload and return a string label for the node. For example::

            labels=str

        could be used to just return a string cast of the node's data payload.
        Or something like::

            labels=lambda node: node['label']

        could be used if the node payloads are dictionaries.
    :param func edge_labels: An optional callback function that will be passed
        an edge payload and return a string label for the edge. For example::

            edge_labels=str

        could be used to just return a string cast of the edge's data payload.
        Or something like::

            edge_labels=lambda edge: edge['label']

        could be used if the edge payloads are dictionaries. If this is set
        edge labels will be drawn in the visualization.
    :param int font_size: An optional fontsize to use for text labels, By
        default a value of 12 is used for nodes and 10 for edges.
    :param str font_color: An optional font color for strings. By default
        ``'k'`` (ie black) is set.
    :param str font_weight: An optional string used to specify the font weight.
        By default a value of ``'normal'`` is used.
    :param str font_family: An optional font family to use for strings. By
        default ``'sans-serif'`` is used.
    :param str label: An optional string label to use for the graph legend.
    :param str connectionstyle: An optional value used to create a curved arc
        of rounding radius rad. For example,
        ``connectionstyle='arc3,rad=0.2'``. See
        :class:`matplotlib.patches.ConnectionStyle` and
        :class:`matplotlib.patches.FancyArrowPatch` for more info. By default
        this is set to ``"arc3"``.

    :returns: A matplotlib figure for the visualization if not running with an
        interactive backend (like in jupyter) or if ``ax`` is not set.
    :rtype: matplotlib.figure.Figure

    For Example:

    .. jupyter-execute::

        import matplotlib.pyplot as plt

        import retworkx
        from retworkx.visualization import mpl_draw

        G = retworkx.generators.directed_path_graph(25)
        mpl_draw(G)
        plt.draw()
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError as e:
        raise ImportError("matplotlib needs to be installed prior to running "
                          "retworkx.visualization.mpl_draw(). You can install "
                          "matplotlib with:\n'pip install matplotlib'") from e
    if ax is None:
        cf = plt.gcf()
    else:
        cf = ax.get_figure()
    cf.set_facecolor("w")
    if ax is None:
        if cf._axstack() is None:
            ax = cf.add_axes((0, 0, 1, 1))
        else:
            ax = cf.gca()

    draw_graph(graph,
               pos=pos,
               ax=ax,
               arrows=arrows,
               with_labels=with_labels,
               **kwds)
    ax.set_axis_off()
    plt.draw_if_interactive()
    if not plt.isinteractive() or ax is None:
        return cf
Example #48
0
def draw_graph(graph, pos=None, arrows=True, with_labels=False, **kwds):
    r"""Draw the graph using Matplotlib.

    Draw the graph with Matplotlib with options for node positions,
    labeling, titles, and many other drawing features.
    See draw() for simple drawing without labels or axes.

    Parameters
    ----------
    graph: A retworkx :class:`~retworkx.PyDiGraph` or
        :class:`~retworkx.PyGraph`

    pos : dictionary, optional
        A dictionary with nodes as keys and positions as values.
        If not specified a spring layout positioning will be computed.
        See :mod:`retworkx.drawing.layout` for functions that
        compute node positions.


    Notes
    -----
    For directed graphs, arrows  are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False.

    """
    try:
        import matplotlib.pyplot as plt
    except ImportError as e:
        raise ImportError("matplotlib needs to be installed prior to running "
                          "retworkx.visualization.mpl_draw(). You can install "
                          "matplotlib with:\n'pip install matplotlib'") from e

    valid_node_kwds = {
        "node_list",
        "node_size",
        "node_color",
        "node_shape",
        "alpha",
        "cmap",
        "vmin",
        "vmax",
        "ax",
        "linewidths",
        "edgecolors",
        "label",
    }

    valid_edge_kwds = {
        "edge_list",
        "width",
        "edge_color",
        "style",
        "alpha",
        "arrowstyle",
        "arrow_size",
        "edge_cmap",
        "edge_vmin",
        "edge_vmax",
        "ax",
        "label",
        "node_size",
        "node_list",
        "node_shape",
        "connectionstyle",
        "min_source_margin",
        "min_target_margin",
    }

    valid_label_kwds = {
        "labels",
        "font_size",
        "font_color",
        "font_family",
        "font_weight",
        "alpha",
        "bbox",
        "ax",
        "horizontalalignment",
        "verticalalignment",
    }

    valid_edge_label_kwds = {
        "edge_labels",
        "font_size",
        "font_color",
        "font_family",
        "font_weight",
        "alpha",
        "bbox",
        "ax",
        "rotate",
        "horizontalalignment",
        "verticalalignment",
    }

    valid_kwds = (valid_node_kwds
                  | valid_edge_kwds
                  | valid_label_kwds
                  | valid_edge_label_kwds)

    if any([k not in valid_kwds for k in kwds]):
        invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
        raise ValueError(f"Received invalid argument(s): {invalid_args}")

    label_fn = kwds.pop("labels", None)
    if label_fn:
        kwds["labels"] = {x: label_fn(graph[x]) for x in graph.node_indexes()}
    edge_label_fn = kwds.pop("edge_labels", None)
    if edge_label_fn:
        kwds["edge_labels"] = {(x[0], x[1]): edge_label_fn(x[2])
                               for x in graph.weighted_edge_list()}

    node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
    edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
    if isinstance(edge_kwds.get("alpha"), list):
        del edge_kwds["alpha"]
    label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
    edge_label_kwds = {
        k: v
        for k, v in kwds.items() if k in valid_edge_label_kwds
    }

    if pos is None:
        pos = retworkx.spring_layout(graph)  # default to spring layout

    draw_nodes(graph, pos, **node_kwds)
    draw_edges(graph, pos, arrows=arrows, **edge_kwds)
    if with_labels:
        draw_labels(graph, pos, **label_kwds)
    if edge_label_fn:
        draw_edge_labels(graph, pos, **edge_label_kwds)
    plt.draw_if_interactive()
Example #49
0
def draw(G, pos=None, ax=None, **kwds):
    """Draw the graph G with Matplotlib.

    Draw the graph as a simple representation with no node
    labels or edge labels and using the full Matplotlib figure area
    and no axis labels by default.  See draw_networkx() for more
    full-featured drawing that allows title, axis labels etc.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See :py:mod:`networkx.drawing.layout` for functions that
       compute node positions.

    ax : Matplotlib Axes object, optional
       Draw the graph in specified Matplotlib axes.

    kwds : optional keywords
       See networkx.draw_networkx() for a description of optional keywords.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> nx.draw(G)
    >>> nx.draw(G, pos=nx.spring_layout(G))  # use spring layout

    See Also
    --------
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()

    Notes
    -----
    This function has the same name as pylab.draw and pyplot.draw
    so beware when using

    >>> from networkx import *

    since you might overwrite the pylab.draw function.

    With pyplot use

    >>> import matplotlib.pyplot as plt
    >>> import networkx as nx
    >>> G = nx.dodecahedral_graph()
    >>> nx.draw(G)  # networkx draw()
    >>> plt.draw()  # pyplot draw()

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        cf = plt.gcf()
    else:
        cf = ax.get_figure()
    cf.set_facecolor('w')
    if ax is None:
        if cf._axstack() is None:
            ax = cf.add_axes((0, 0, 1, 1))
        else:
            ax = cf.gca()

    if 'with_labels' not in kwds:
        kwds['with_labels'] = 'labels' in kwds

    try:
        draw_networkx(G, pos=pos, ax=ax, **kwds)
        ax.set_axis_off()
        plt.draw_if_interactive()
    except:
        raise
    return
Example #50
0
def draw_networkx(G, pos=None, arrows=True, with_labels=True, **kwds):
    """Draw the graph G using Matplotlib.

    Draw the graph with Matplotlib with options for node positions,
    labeling, titles, and many other drawing features.
    See draw() for simple drawing without labels or axes.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See :py:mod:`networkx.drawing.layout` for functions that
       compute node positions.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.

    arrowstyle : str, optional (default='-|>')
        For directed graphs, choose the style of the arrowsheads.
        See :py:class: `matplotlib.patches.ArrowStyle` for more
        options.

    arrowsize : int, optional (default=10)
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.

    with_labels :  bool, optional (default=True)
       Set to True to draw labels on the nodes.

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    nodelist : list, optional (default G.nodes())
       Draw only specified nodes

    edgelist : list, optional (default=G.edges())
       Draw only specified edges

    node_size : scalar or array, optional (default=300)
       Size of nodes.  If an array is specified it must be the
       same length as nodelist.

    node_color : color string, or array of floats, (default='#1f78b4')
       Node color. Can be a single color format string,
       or a  sequence of colors with the same length as nodelist.
       If numeric values are specified they will be mapped to
       colors using the cmap and vmin,vmax parameters.  See
       matplotlib.scatter for more details.

    node_shape :  string, optional (default='o')
       The shape of the node.  Specification is as matplotlib.scatter
       marker, one of 'so^>v<dph8'.

    alpha : float, optional (default=1.0)
       The node and edge transparency

    cmap : Matplotlib colormap, optional (default=None)
       Colormap for mapping intensities of nodes

    vmin,vmax : float, optional (default=None)
       Minimum and maximum for node colormap scaling

    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)

    width : float, optional (default=1.0)
       Line width of edges

    edge_color : color string, or array of floats (default='r')
       Edge color. Can be a single color format string,
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    edge_cmap : Matplotlib colormap, optional (default=None)
       Colormap for mapping intensities of edges

    edge_vmin,edge_vmax : floats, optional (default=None)
       Minimum and maximum for edge colormap scaling

    style : string, optional (default='solid')
       Edge line style (solid|dashed|dotted,dashdot)

    labels : dictionary, optional (default=None)
       Node labels in a dictionary keyed by node of text labels

    font_size : int, optional (default=12)
       Font size for text labels

    font_color : string, optional (default='k' black)
       Font color string

    font_weight : string, optional (default='normal')
       Font weight

    font_family : string, optional (default='sans-serif')
       Font family

    label : string, optional
        Label for graph legend

    Notes
    -----
    For directed graphs, arrows  are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> nx.draw(G)
    >>> nx.draw(G, pos=nx.spring_layout(G))  # use spring layout

    >>> import matplotlib.pyplot as plt
    >>> limits = plt.axis('off')  # turn of axis

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if pos is None:
        pos = nx.drawing.spring_layout(G)  # default to spring layout

    node_collection = draw_networkx_nodes(G, pos, **kwds)
    edge_collection = draw_networkx_edges(G, pos, arrows=arrows, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    plt.draw_if_interactive()
Example #51
0
    def plot_operator_counts(self, figure=None, title=None, legend=None,
                             **kwargs):
        """
        Plots an overview of the destroy and repair operators' performance.

        Parameters
        ----------
        figure : Figure
            Optional figure. If not passed, a new figure is constructed, and
            some default margins are set.
        title : str
            Optional figure title. When not passed, no title is set.
        legend : list
            Optional legend entries. When passed, this should be a list of at
            most four strings. The first string describes the number of times
            a best solution was found, the second a better, the third a solution
            was accepted but did not improve upon the current or global best,
            and the fourth the number of times a solution was rejected. If less
            than four strings are passed, only the first len(legend) count types
            are plotted. When not passed, a sensible default is set and all
            counts are shown.
        kwargs : dict
            Optional arguments passed to each call of ``ax.barh``.

        Raises
        ------
        ValueError
            When the legend contains more than four elements.
        """
        if figure is None:
            figure, (d_ax, r_ax) = plt.subplots(nrows=2)

            # Ensures there is generally sufficient white space between the
            # operator subplots, and we have some space to put the legend. When
            # a figure is passed-in, these sorts of modifications are assumed
            # to have been performed at the call site.
            figure.subplots_adjust(hspace=0.7, bottom=0.2)
        else:
            d_ax, r_ax = figure.subplots(nrows=2)

        if title is not None:
            figure.suptitle(title)

        if legend is None:
            legend = ["Best", "Better", "Accepted", "Rejected"]
        elif len(legend) > 4:
            raise ValueError("Legend not understood. Expected at most 4 items,"
                             " found {0}.".format(len(legend)))

        self._plot_operator_counts(d_ax,
                                   self.statistics.destroy_operator_counts,
                                   "Destroy operators",
                                   len(legend),
                                   **kwargs)

        self._plot_operator_counts(r_ax,
                                   self.statistics.repair_operator_counts,
                                   "Repair operators",
                                   len(legend),
                                   **kwargs)

        figure.legend(legend, ncol=len(legend), loc="lower center")

        plt.draw_if_interactive()
Example #52
0
    def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
        """
        Make a scatter plot of circles. 
        Similar to plt.scatter, but the size of circles are in data scale.

        Parameters
        ----------
        x, y : scalar or array_like, shape (n, )
            Input data
        s : scalar or array_like, shape (n, ) 
            Radius of circles.
        c : color or sequence of color, optional, default : 'b'
            `c` can be a single color format string, or a sequence of color
            specifications of length `N`, or a sequence of `N` numbers to be
            mapped to colors using the `cmap` and `norm` specified via kwargs.
            Note that `c` should not be a single numeric RGB or RGBA sequence 
            because that is indistinguishable from an array of values
            to be colormapped. (If you insist, use `color` instead.)  
            `c` can be a 2-D array in which the rows are RGB or RGBA, however. 
        vmin, vmax : scalar, optional, default: None
            `vmin` and `vmax` are used in conjunction with `norm` to normalize
            luminance data.  If either are `None`, the min and max of the
            color array is used.
        kwargs : `~matplotlib.collections.Collection` properties
            Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw),
            linestyle(ls), norm, cmap, transform, etc.

        Returns
        -------
        paths : `~matplotlib.collections.PathCollection`
        """

        if np.isscalar(c):
            kwargs.setdefault('color', c)
            c = None

        if 'fc' in kwargs:
            kwargs.setdefault('facecolor', kwargs.pop('fc'))
        if 'ec' in kwargs:
            kwargs.setdefault('edgecolor', kwargs.pop('ec'))
        if 'ls' in kwargs:
            kwargs.setdefault('linestyle', kwargs.pop('ls'))
        if 'lw' in kwargs:
            kwargs.setdefault('linewidth', kwargs.pop('lw'))
        # You can set `facecolor` with an array for each patch,
        # while you can only set `facecolors` with a value for all.

        zipped = np.broadcast(x, y, s)
        patches = [Circle((x_, y_), s_) for x_, y_, s_ in zipped]
        collection = PatchCollection(patches, **kwargs)
        if c is not None:
            c = np.broadcast_to(c, zipped.shape).ravel()
            collection.set_array(c)
            collection.set_clim(vmin, vmax)

        ax = plt.gca()
        ax.add_collection(collection)
        ax.autoscale_view()
        plt.draw_if_interactive()
        if c is not None:
            plt.sci(collection)
        return collection
Example #53
0
    def add_graph(self,
                  adjacency_matrix,
                  node_coords,
                  node_color='auto',
                  node_size=50,
                  edge_cmap=cm.bwr,
                  edge_vmin=None,
                  edge_vmax=None,
                  edge_threshold=None,
                  edge_kwargs=None,
                  node_kwargs=None):
        """Plot undirected graph on each of the axes

            Parameters
            ----------
            adjacency_matrix: numpy array of shape (n, n)
                represents the edges strengths of the graph. Assumed to be
                a symmetric matrix.
            node_coords: numpy array_like of shape (n, 3)
                3d coordinates of the graph nodes in world space.
            node_color: color or sequence of colors
                color(s) of the nodes.
            node_size: scalar or array_like
                size(s) of the nodes in points^2.
            edge_cmap: colormap
                colormap used for representing the strength of the edges.
            edge_vmin: float, optional, default: None
            edge_vmax: float, optional, default: None
                If not None, either or both of these values will be used to
                as the minimum and maximum values to color edges. If None are
                supplied the maximum absolute value within the given threshold
                will be used as minimum (multiplied by -1) and maximum
                coloring levels.
            edge_threshold: str or number
                If it is a number only the edges with a value greater than
                edge_threshold will be shown.
                If it is a string it must finish with a percent sign,
                e.g. "25.3%", and only the edges with a abs(value) above
                the given percentile will be shown.
            edge_kwargs: dict
                will be passed as kwargs for each edge matlotlib Line2D.
            node_kwargs: dict
                will be passed as kwargs to the plt.scatter call that plots all
                the nodes in one go.

        """
        # set defaults
        if edge_kwargs is None:
            edge_kwargs = {}
        if node_kwargs is None:
            node_kwargs = {}
        if node_color == 'auto':
            nb_nodes = len(node_coords)
            node_color = mpl_cm.Set2(np.linspace(0, 1, nb_nodes))

        node_coords = np.asarray(node_coords)

        # decompress input matrix if sparse
        if sparse.issparse(adjacency_matrix):
            adjacency_matrix = adjacency_matrix.toarray()

        # make the lines below well-behaved
        adjacency_matrix = np.nan_to_num(adjacency_matrix)

        # safety checks
        if 's' in node_kwargs:
            raise ValueError("Please use 'node_size' and not 'node_kwargs' "
                             "to specify node sizes")
        if 'c' in node_kwargs:
            raise ValueError("Please use 'node_color' and not 'node_kwargs' "
                             "to specify node colors")

        adjacency_matrix_shape = adjacency_matrix.shape
        if (len(adjacency_matrix_shape) != 2
                or adjacency_matrix_shape[0] != adjacency_matrix_shape[1]):
            raise ValueError(
                "'adjacency_matrix' is supposed to have shape (n, n)."
                ' Its shape was {0}'.format(adjacency_matrix_shape))

        node_coords_shape = node_coords.shape
        if len(node_coords_shape) != 2 or node_coords_shape[1] != 3:
            message = (
                "Invalid shape for 'node_coords'. You passed an "
                "'adjacency_matrix' of shape {0} therefore "
                "'node_coords' should be a array with shape ({0[0]}, 3) "
                'while its shape was {1}').format(adjacency_matrix_shape,
                                                  node_coords_shape)

            raise ValueError(message)

        if node_coords_shape[0] != adjacency_matrix_shape[0]:
            raise ValueError(
                "Shape mismatch between 'adjacency_matrix' "
                "and 'node_coords'"
                "'adjacency_matrix' shape is {0}, 'node_coords' shape is {1}".
                format(adjacency_matrix_shape, node_coords_shape))

        if not np.allclose(adjacency_matrix, adjacency_matrix.T, rtol=1e-3):
            raise ValueError("'adjacency_matrix' should be symmetric")

        # For a masked array, masked values are replaced with zeros
        if hasattr(adjacency_matrix, 'mask'):
            if not (adjacency_matrix.mask == adjacency_matrix.mask.T).all():
                raise ValueError(
                    "'adjacency_matrix' was masked with a non symmetric mask")
            adjacency_matrix = adjacency_matrix.filled(0)

        if edge_threshold is not None:
            if isinstance(edge_threshold, _basestring):
                message = ("If 'edge_threshold' is given as a string it "
                           'should be a number followed by the percent sign, '
                           'e.g. "25.3%"')
                if not edge_threshold.endswith('%'):
                    raise ValueError(message)

                try:
                    percentile = float(edge_threshold[:-1])
                except ValueError as exc:
                    exc.args += (message, )
                    raise

                # Keep a percentile of edges with the highest absolute
                # values, so only need to look at the covariance
                # coefficients below the diagonal
                lower_diagonal_indices = np.tril_indices_from(adjacency_matrix,
                                                              k=-1)
                lower_diagonal_values = adjacency_matrix[
                    lower_diagonal_indices]
                edge_threshold = stats.scoreatpercentile(
                    np.abs(lower_diagonal_values), percentile)

            elif not isinstance(edge_threshold, numbers.Real):
                raise TypeError('edge_threshold should be either a number '
                                'or a string finishing with a percent sign')

            adjacency_matrix = adjacency_matrix.copy()
            threshold_mask = np.abs(adjacency_matrix) < edge_threshold
            adjacency_matrix[threshold_mask] = 0

        lower_triangular_adjacency_matrix = np.tril(adjacency_matrix, k=-1)
        non_zero_indices = lower_triangular_adjacency_matrix.nonzero()

        line_coords = [
            node_coords[list(index)] for index in zip(*non_zero_indices)
        ]

        adjacency_matrix_values = adjacency_matrix[non_zero_indices]
        for ax in self.axes.values():
            ax._add_markers(node_coords, node_color, node_size, **node_kwargs)
            if line_coords:
                ax._add_lines(line_coords,
                              adjacency_matrix_values,
                              edge_cmap,
                              vmin=edge_vmin,
                              vmax=edge_vmax,
                              **edge_kwargs)

        plt.draw_if_interactive()
Example #54
0
 def draw(self):
     plt.draw_if_interactive()
Example #55
0
def draw_networkx(G, pos=None, arrows=True, with_labels=True, **kwds):
    """Draw the graph G using Matplotlib.

    Draw the graph with Matplotlib with options for node positions,
    labeling, titles, and many other drawing features.
    See draw() for simple drawing without labels or axes.

    Parameters
    ----------
    G : graph
        A networkx graph

    pos : dictionary, optional
        A dictionary with nodes as keys and positions as values.
        If not specified a spring layout positioning will be computed.
        See :py:mod:`networkx.drawing.layout` for functions that
        compute node positions.

    arrows : bool (default=True)
        For directed graphs, if True draw arrowheads.
        Note: Arrows will be the same color as edges.

    arrowstyle : str (default='-\|>')
        For directed graphs, choose the style of the arrowsheads.
        See `matplotlib.patches.ArrowStyle` for more options.

    arrowsize : int (default=10)
        For directed graphs, choose the size of the arrow head's length and
        width. See `matplotlib.patches.FancyArrowPatch` for attribute
        `mutation_scale` for more info.

    with_labels :  bool (default=True)
        Set to True to draw labels on the nodes.

    ax : Matplotlib Axes object, optional
        Draw the graph in the specified Matplotlib axes.

    nodelist : list (default=list(G))
        Draw only specified nodes

    edgelist : list (default=list(G.edges()))
        Draw only specified edges

    node_size : scalar or array (default=300)
        Size of nodes.  If an array is specified it must be the
        same length as nodelist.

    node_color : color or array of colors (default='#1f78b4')
        Node color. Can be a single color or a sequence of colors with the same
        length as nodelist. Color can be string or rgb (or rgba) tuple of
        floats from 0-1. If numeric values are specified they will be
        mapped to colors using the cmap and vmin,vmax parameters. See
        matplotlib.scatter for more details.

    node_shape :  string (default='o')
        The shape of the node.  Specification is as matplotlib.scatter
        marker, one of 'so^>v<dph8'.

    alpha : float or None (default=None)
        The node and edge transparency

    cmap : Matplotlib colormap, optional
        Colormap for mapping intensities of nodes

    vmin,vmax : float, optional
        Minimum and maximum for node colormap scaling

    linewidths : scalar or sequence (default=1.0)
        Line width of symbol border

    width : float or array of floats (default=1.0)
        Line width of edges

    edge_color : color or array of colors (default='k')
        Edge color. Can be a single color or a sequence of colors with the same
        length as edgelist. Color can be string or rgb (or rgba) tuple of
        floats from 0-1. If numeric values are specified they will be
        mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    edge_cmap : Matplotlib colormap, optional
        Colormap for mapping intensities of edges

    edge_vmin,edge_vmax : floats, optional
        Minimum and maximum for edge colormap scaling

    style : string (default=solid line)
        Edge line style e.g.: '-', '--', '-.', ':'
        or words like 'solid' or 'dashed'.
        (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)

    labels : dictionary (default=None)
        Node labels in a dictionary of text labels keyed by node

    font_size : int (default=12 for nodes, 10 for edges)
        Font size for text labels

    font_color : string (default='k' black)
        Font color string

    font_weight : string (default='normal')
        Font weight

    font_family : string (default='sans-serif')
        Font family

    label : string, optional
        Label for graph legend

    kwds : optional keywords
        See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
        networkx.draw_networkx_labels() for a description of optional keywords.

    Notes
    -----
    For directed graphs, arrows  are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> nx.draw(G)
    >>> nx.draw(G, pos=nx.spring_layout(G))  # use spring layout

    >>> import matplotlib.pyplot as plt
    >>> limits = plt.axis("off")  # turn off axis

    Also see the NetworkX drawing examples at
    https://networkx.org/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw
    draw_networkx_nodes
    draw_networkx_edges
    draw_networkx_labels
    draw_networkx_edge_labels
    """
    import matplotlib.pyplot as plt

    valid_node_kwds = (
        "nodelist",
        "node_size",
        "node_color",
        "node_shape",
        "alpha",
        "cmap",
        "vmin",
        "vmax",
        "ax",
        "linewidths",
        "edgecolors",
        "label",
    )

    valid_edge_kwds = (
        "edgelist",
        "width",
        "edge_color",
        "style",
        "alpha",
        "arrowstyle",
        "arrowsize",
        "edge_cmap",
        "edge_vmin",
        "edge_vmax",
        "ax",
        "label",
        "node_size",
        "nodelist",
        "node_shape",
        "connectionstyle",
        "min_source_margin",
        "min_target_margin",
    )

    valid_label_kwds = (
        "labels",
        "font_size",
        "font_color",
        "font_family",
        "font_weight",
        "alpha",
        "bbox",
        "ax",
        "horizontalalignment",
        "verticalalignment",
    )

    valid_kwds = valid_node_kwds + valid_edge_kwds + valid_label_kwds

    if any([k not in valid_kwds for k in kwds]):
        invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
        raise ValueError(f"Received invalid argument(s): {invalid_args}")

    node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
    edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
    label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}

    if pos is None:
        pos = nx.drawing.spring_layout(G)  # default to spring layout

    draw_networkx_nodes(G, pos, **node_kwds)
    draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **label_kwds)
    plt.draw_if_interactive()
Example #56
0
def ellipses(x, y, w, h=None, rot=0.0, c='b', vmin=None, vmax=None, **kwargs):
    """Make a scatter plot of ellipses

    Parameters
    ----------
    x, y : scalar or array_like, shape (n, )
        Center of ellipses.
    w, h : scalar or array_like, shape (n, )
        Total length (diameter) of horizontal/vertical axis.
        `h` is set to be equal to `w` by default, ie. circle.
    rot : scalar or array_like, shape (n, )
        Rotation in degrees (anti-clockwise).
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)
        `c` can be a 2-D array in which the rows are RGB or RGBA, however.
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls),
        norm, cmap, transform, etc.

    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`

    Examples
    --------
    >>> a = np.arange(11)
    >>> ellipses(a, a, w=4, h=a, rot=a*30, c=a, alpha=0.5, ec='none')
    >>> plt.colorbar()

    References
    ----------
    With thanks to https://gist.github.com/syrte/592a062c562cd2a98a83
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    from matplotlib.collections import PatchCollection

    if np.isscalar(c):
        kwargs.setdefault('color', c)
        c = None

    if 'fc' in kwargs:
        kwargs.setdefault('facecolor', kwargs.pop('fc'))
    if 'ec' in kwargs:
        kwargs.setdefault('edgecolor', kwargs.pop('ec'))
    if 'ls' in kwargs:
        kwargs.setdefault('linestyle', kwargs.pop('ls'))
    if 'lw' in kwargs:
        kwargs.setdefault('linewidth', kwargs.pop('lw'))
    # You can set `facecolor` with an array for each patch,
    # while you can only set `facecolors` with a value for all.

    if h is None:
        h = w

    zipped = np.broadcast(x, y, w, h, rot)
    patches = [
        Ellipse((x_, y_), w_, h_, rot_) for x_, y_, w_, h_, rot_ in zipped
    ]
    collection = PatchCollection(patches, **kwargs)
    if c is not None:
        c = np.broadcast_to(c, zipped.shape).ravel()
        collection.set_array(c)
        collection.set_clim(vmin, vmax)

    ax = plt.gca()
    ax.add_collection(collection)
    ax.autoscale_view()
    plt.draw_if_interactive()
    if c is not None:
        plt.sci(collection)
    return collection
Example #57
0
def draw(G, pos=None, ax=None, hold=None, **kwds):
    """Draw the graph G with Matplotlib.

    Draw the graph as a simple representation with no node
    labels or edge labels and using the full Matplotlib figure area
    and no axis labels by default.  See draw_networkx() for more
    full-featured drawing that allows title, axis labels etc.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See networkx.layout for functions that compute node positions.

    ax : Matplotlib Axes object, optional
       Draw the graph in specified Matplotlib axes.

    hold : bool, optional
       Set the Matplotlib hold state.  If True subsequent draw
       commands will be added to the current axes.

    **kwds : optional keywords
       See networkx.draw_networkx() for a description of optional keywords.


    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> nx.draw(G)
    >>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout

    See Also
    --------
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()

    Notes
    -----
    This function has the same name as pylab.draw and pyplot.draw
    so beware when using

    >>> from networkx import *

    since you might overwrite the pylab.draw function.

    With pyplot use

    >>> import matplotlib.pyplot as plt
    >>> import networkx as nx
    >>> G=nx.dodecahedral_graph()
    >>> nx.draw(G)  # networkx draw()
    >>> plt.draw()  # pyplot draw()

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        cf = plt.gcf()
    else:
        cf = ax.get_figure()
    cf.set_facecolor('w')
    if ax is None:
        if cf._axstack() is None:
            ax = cf.add_axes((0, 0, 1, 1))
        else:
            ax = cf.gca()

# allow callers to override the hold state by passing hold=True|False

    if 'with_labels' not in kwds:
        kwds['with_labels'] = False
    b = plt.ishold()
    h = kwds.pop('hold', None)
    if h is not None:
        plt.hold(h)
    try:
        draw_networkx(G, pos=pos, ax=ax, **kwds)
        ax.set_axis_off()
        plt.draw_if_interactive()
    except:
        plt.hold(b)
        raise
    plt.hold(b)
    return
Example #58
0
def PlotTargets(src_nrn,
                tgt_layer,
                syn_type=None,
                fig=None,
                mask=None,
                probability_parameter=None,
                src_color='red',
                src_size=50,
                tgt_color='blue',
                tgt_size=20,
                mask_color='yellow',
                probability_cmap='Greens'):
    """
    Plot all targets of source neuron `src_nrn` in a target layer `tgt_layer`.

    Parameters
    ----------
    src_nrn : NodeCollection
        `NodeCollection` of source neuron (as single-element NodeCollection)
    tgt_layer : NodeCollection
        `NodeCollection` of tgt_layer
    syn_type : [None | str], optional, default: None
        Show only targets connected with a given synapse type
    fig : [None | matplotlib.figure.Figure object], optional, default: None
        Matplotlib figure to plot to. If not given, a new figure is created.
    mask : [None | dict], optional, default: None
        Draw mask with targets; see :py:func:`.PlotProbabilityParameter` for details.
    probability_parameter : [None | Parameter], optional, default: None
        Draw connection probability with targets; see :py:func:`.PlotProbabilityParameter` for details.
    src_color : [None | any matplotlib color], optional, default: 'red'
        Color used to mark source node position
    src_size : float, optional, default: 50
        Size of source marker (see scatter for details)
    tgt_color : [None | any matplotlib color], optional, default: 'blue'
        Color used to mark target node positions
    tgt_size : float, optional, default: 20
        Size of target markers (see scatter for details)
    mask_color : [None | any matplotlib color], optional, default: 'red'
        Color used for line marking mask
    probability_cmap : [None | any matplotlib cmap color], optional, default: 'Greens'
        Color used for lines marking probability parameter.

    Returns
    -------
    matplotlib.figure.Figure object

    See also
    --------
    GetTargetNodes: Obtain targets of a sources in a given target layer.
    GetTargetPositions: Obtain positions of targets of sources in a given target layer.
    probability_parameter: Add indication of connection probability and mask to axes.
    PlotLayer: Plot all nodes in a spatially distributed population.
    matplotlib.pyplot.scatter : matplotlib scatter plot.

    Notes
    -----
    * Do **not** use this function in distributed simulations.

    **Example**
        ::

            import nest
            import matplotlib.pyplot as plt

            # create a spatial population
            s_nodes = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[11, 11], extent=[11., 11.]))

            # connectivity specifications with a mask
            conndict = {'rule': 'pairwise_bernoulli', 'p': 1.,
                        'mask': {'rectangular': {'lower_left' : [-2.0, -1.0],
                                                 'upper_right': [2.0, 1.0]}}}

            # connect population s_nodes with itself according to the given
            # specifications
            nest.Connect(s_nodes, s_nodes, conndict)

            # plot the targets of a source neuron
            nest.PlotTargets(s_nodes[4], s_nodes)
            plt.show()
    """

    # import pyplot here and not at toplevel to avoid preventing users
    # from changing matplotlib backend after importing nest
    import matplotlib.pyplot as plt

    if not HAVE_MPL:
        raise ImportError("Matplotlib could not be imported")

    if not isinstance(src_nrn, NodeCollection) or len(src_nrn) != 1:
        raise TypeError("src_nrn must be a single element NodeCollection.")
    if not isinstance(tgt_layer, NodeCollection):
        raise TypeError("tgt_layer must be a NodeCollection.")

    # get position of source
    srcpos = GetPosition(src_nrn)

    # get layer extent
    ext = tgt_layer.spatial['extent']

    if len(ext) == 2:
        # 2D layer

        # get layer extent and center, x and y
        xext, yext = ext
        xctr, yctr = tgt_layer.spatial['center']

        if fig is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        else:
            ax = fig.gca()

        # get positions, reorganize to x and y vectors
        tgtpos = GetTargetPositions(src_nrn, tgt_layer, syn_type)
        if tgtpos:
            xpos, ypos = zip(*tgtpos[0])
            ax.scatter(xpos, ypos, s=tgt_size, facecolor=tgt_color)

        ax.scatter(srcpos[:1],
                   srcpos[1:],
                   s=src_size,
                   facecolor=src_color,
                   alpha=0.4,
                   zorder=-10)

        if mask is not None or probability_parameter is not None:
            edges = [xctr - xext, xctr + xext, yctr - yext, yctr + yext]
            PlotProbabilityParameter(src_nrn,
                                     probability_parameter,
                                     mask=mask,
                                     edges=edges,
                                     ax=ax,
                                     prob_cmap=probability_cmap,
                                     mask_color=mask_color)

        _draw_extent(ax, xctr, yctr, xext, yext)

    else:
        # 3D layer
        from mpl_toolkits.mplot3d import Axes3D

        if fig is None:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
        else:
            ax = fig.gca()

        # get positions, reorganize to x,y,z vectors
        tgtpos = GetTargetPositions(src_nrn, tgt_layer, syn_type)
        if tgtpos:
            xpos, ypos, zpos = zip(*tgtpos[0])
            ax.scatter3D(xpos, ypos, zpos, s=tgt_size, facecolor=tgt_color)

        ax.scatter3D(srcpos[:1],
                     srcpos[1:2],
                     srcpos[2:],
                     s=src_size,
                     facecolor=src_color,
                     alpha=0.4,
                     zorder=-10)

    plt.draw_if_interactive()

    return fig
Example #59
0
def PlotLayer(layer, fig=None, nodecolor='b', nodesize=20):
    """
    Plot all nodes in a `layer`.

    Parameters
    ----------
    layer : NodeCollection
        `NodeCollection` of spatially distributed nodes
    fig : [None | matplotlib.figure.Figure object], optional, default: None
        Matplotlib figure to plot to. If not given, a new figure is
        created.
    nodecolor : [None | any matplotlib color], optional, default: 'b'
        Color for nodes
    nodesize : float, optional, default: 20
        Marker size for nodes

    Returns
    -------
    `matplotlib.figure.Figure` object

    See also
    --------
    PlotProbabilityParameter: Create a plot of the connection probability and/or mask.
    PlotTargets: Plot all targets of a given source.
    matplotlib.figure.Figure : matplotlib Figure class

    Notes
    -----
    * Do **not** use this function in distributed simulations.


    Example
    -------
        ::

            import nest
            import matplotlib.pyplot as plt

            # create a spatial population
            s_nodes = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[11, 11], extent=[11., 11.]))

            # plot layer with all its nodes
            nest.PlotLayer(s_nodes)
            plt.show()
    """

    # import pyplot here and not at toplevel to avoid preventing users
    # from changing matplotlib backend after importing nest
    import matplotlib.pyplot as plt

    if not HAVE_MPL:
        raise ImportError('Matplotlib could not be imported')

    if not isinstance(layer, NodeCollection):
        raise TypeError('layer must be a NodeCollection.')

    # get layer extent
    ext = layer.spatial['extent']

    if len(ext) == 2:
        # 2D layer

        # get layer extent and center, x and y
        xext, yext = ext
        xctr, yctr = layer.spatial['center']

        # extract position information, transpose to list of x and y pos
        xpos, ypos = zip(*GetPosition(layer))

        if fig is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        else:
            ax = fig.gca()

        ax.scatter(xpos, ypos, s=nodesize, facecolor=nodecolor)
        _draw_extent(ax, xctr, yctr, xext, yext)

    elif len(ext) == 3:
        # 3D layer
        from mpl_toolkits.mplot3d import Axes3D

        # extract position information, transpose to list of x,y,z pos
        pos = zip(*GetPosition(layer))

        if fig is None:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
        else:
            ax = fig.gca()

        ax.scatter(*pos, s=nodesize, c=nodecolor)
        plt.draw_if_interactive()

    else:
        raise ValueError("unexpected dimension of layer")

    return fig
Example #60
0
def rectangles(x,
               y,
               w,
               h=None,
               rot=0.0,
               c='b',
               vmin=None,
               vmax=None,
               **kwargs):
    """
    Make a scatter plot of rectangles.
    
    Parameters
    ----------
    x, y : scalar or array_like, shape (n, )
        Center of rectangles.
    w, h : scalar or array_like, shape (n, )
        Width, Height.
        `h` is set to be equal to `w` by default, ie. squares.
    rot : scalar or array_like, shape (n, )
        Rotation in degrees (anti-clockwise).
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)
        `c` can be a 2-D array in which the rows are RGB or RGBA, however.
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls),
        norm, cmap, transform, etc.
        
    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`
    
    Examples
    --------
    a = np.arange(11)
    rectangles(a, a, w=5, h=6, rot=a*30, c=a, alpha=0.5, ec='none')
    plt.colorbar()
    
    License
    --------
    This code is under [The BSD 3-Clause License]
    (http://opensource.org/licenses/BSD-3-Clause)
    """
    if np.isscalar(c):
        kwargs.setdefault('color', c)
        c = None
    if 'fc' in kwargs:
        kwargs.setdefault('facecolor', kwargs.pop('fc'))
    if 'ec' in kwargs:
        kwargs.setdefault('edgecolor', kwargs.pop('ec'))
    if 'ls' in kwargs:
        kwargs.setdefault('linestyle', kwargs.pop('ls'))
    if 'lw' in kwargs:
        kwargs.setdefault('linewidth', kwargs.pop('lw'))
    # You can set `facecolor` with an array for each patch,
    # while you can only set `facecolors` with a value for all.

    if h is None:
        h = w
    d = np.sqrt(np.square(w) + np.square(h)) / 2.
    t = np.deg2rad(rot) + np.arctan2(h, w)
    x, y = x - d * np.cos(t), y - d * np.sin(t)
    patches = [
        Rectangle((x_, y_), w_, h_, rot_)
        for x_, y_, w_, h_, rot_ in np.broadcast(x, y, w, h, rot)
    ]
    collection = PatchCollection(patches, **kwargs)
    if c is not None:
        collection.set_array(np.asarray(c))
        collection.set_clim(vmin, vmax)

    ax = plt.gca()
    ax.add_collection(collection)
    ax.autoscale_view()
    plt.draw_if_interactive()
    if c is not None:
        plt.sci(collection)
    return collection