Пример #1
0
    def drawall(self, **kwargs):
        if not self.n == self.drawax.shape:
            self.drawax = np.ones(self.n, dtype='bool')
        if not self.n[1] == self.hrel.shape[0]:
            self.hrel = np.ones(self.n[1], dtype='float32')
        if not self.n[0] == self.vrel.shape[0]:
            self.vrel = np.ones(self.n[0], dtype='float32')
        if kwargs.has_key('lw'):
            kwargs['linewidth'] = kwargs.pop('lw')
        if not kwargs.has_key('linewidth'):
            kwargs['linewidth'] = self.linewidth
        else:
            self.linewidth = kwargs['linewidth']

        forcesharex = False
        forcesharey = False
        if kwargs.has_key('sharex'):
            forcesharex = True
        if kwargs.has_key('sharey'):
            forcesharey = True
        inter = pylab.isinteractive()
        pylab.interactive(
            False)  # wait to draw the axes, until they've all been created.
        axg = self.axgrid()
        for iv in range(self.n[0]):
            for ih in range(self.n[1]):
                if forcesharex:  # I should put this functionality into a func.
                    pass
                elif self.sharex[iv, ih] and self._sharex_ax[self.sharex[iv,
                                                                         ih]]:
                    kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]]
                elif kwargs.has_key('sharex'):
                    kwargs.pop('sharex')
                if forcesharey:
                    pass
                elif self.sharey[iv, ih] and self._sharey_ax[self.sharey[iv,
                                                                         ih]]:
                    kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]]
                elif kwargs.has_key('sharey'):
                    kwargs.pop('sharey')
                if self.drawax[iv, ih]:
                    #self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs)
                    self.ax[iv, ih] = axes(axg[iv, ih, :], **kwargs)
                    self.ax[iv, ih].hold(True)
                    if self.sharex[
                            iv,
                            ih] and not self._sharex_ax[self.sharex[iv, ih]]:
                        self._sharex_ax[self.sharex[iv, ih]] = self.ax[iv, ih]
                    if self.sharey[
                            iv,
                            ih] and not self._sharey_ax[self.sharey[iv, ih]]:
                        self._sharey_ax[self.sharey[iv, ih]] = self.ax[iv, ih]

                flag = True

        self._xlabel_ax = self.ax[-1, 0]
        self._ylabel_ax = self._xlabel_ax
        pylab.interactive(inter)
        pylab.draw_if_interactive()
        return self.ax
Пример #2
0
    def drawall(self, **kwargs):
        if not self.n == self.drawax.shape:
            self.drawax = np.ones(self.n, dtype='bool')
        if 'lw' in kwargs.keys():
            kwargs['linewidth'] = kwargs.pop('lw', self.linewidth)
        if 'linewidth' not in kwargs.keys():
            kwargs['linewidth'] = self.linewidth
        else:
            self.linewidth = kwargs['linewidth']

        inter = pylab.isinteractive()
        pylab.interactive(False)
                          # wait to draw the axes, until they've all been
                          # created.
        for iv, ih in self._iter_axinds():
            if self.drawax[iv, ih]:
                self.ax[iv, ih] = axes(self.axPlacer(iv, ih),
                                       sharex=self.sharex(iv, ih),
                                       sharey=self.sharey(iv, ih),
                                       **kwargs)
        self._xlabel_ax = self.ax[-1, 0]
        self._ylabel_ax = self._xlabel_ax
        pylab.interactive(inter)
        pylab.draw_if_interactive()
        return self.ax
Пример #3
0
    def drawall(self, **kwargs):
        if not self.n == self.drawax.shape:
            self.drawax = np.ones(self.n, dtype='bool')
        if 'lw' in kwargs.keys():
            kwargs['linewidth'] = kwargs.pop('lw', self.linewidth)
        if 'linewidth' not in kwargs.keys():
            kwargs['linewidth'] = self.linewidth
        else:
            self.linewidth = kwargs['linewidth']

        inter = pylab.isinteractive()
        pylab.interactive(False)
        # wait to draw the axes, until they've all been
        # created.
        for iv, ih in self._iter_axinds():
            if self.drawax[iv, ih]:
                self.ax[iv, ih] = axes(self.axPlacer(iv, ih),
                                       sharex=self.sharex(iv, ih),
                                       sharey=self.sharey(iv, ih),
                                       **kwargs)
        self._xlabel_ax = self.ax[-1, 0]
        self._ylabel_ax = self._xlabel_ax
        pylab.interactive(inter)
        pylab.draw_if_interactive()
        return self.ax
Пример #4
0
def draw_networkx(G, pos, with_labels=True, **kwds):
    """Draw the graph G with given node positions pos

    Usage:

    >>> from networkx_v099 import *
    >>> import pylab as P
    >>> ax=P.subplot(111)
    >>> G=dodecahedral_graph()
    >>> pos=spring_layout(G)
    >>> draw_networkx(G,pos,ax=ax)

    This is same as 'draw' but the node positions *must* be
    specified in the variable pos.
    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx_v099.layout for functions that compute node positions.

    An optional matplotlib axis can be provided through the
    optional keyword ax.

    with_labels contols text labeling of the nodes

    Also see:

    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    """
    from matplotlib.pylab import draw_if_interactive 
    node_collection=draw_networkx_nodes(G, pos, **kwds)
    edge_collection=draw_networkx_edges(G, pos, **kwds) 
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    draw_if_interactive()
Пример #5
0
def format_dateaxis(subplot, freq):
    """
    Pretty-formats the date axis (x-axis).

    Major and minor ticks are automatically set for the frequency of the
    current underlying series.  As the dynamic mode is activated by
    default, changing the limits of the x axis will intelligently change
    the positions of the ticks.
    """
    majlocator = TimeSeries_DateLocator(freq,
                                        dynamic_mode=True,
                                        minor_locator=False,
                                        plot_obj=subplot)
    minlocator = TimeSeries_DateLocator(freq,
                                        dynamic_mode=True,
                                        minor_locator=True,
                                        plot_obj=subplot)
    subplot.xaxis.set_major_locator(majlocator)
    subplot.xaxis.set_minor_locator(minlocator)

    majformatter = TimeSeries_DateFormatter(freq,
                                            dynamic_mode=True,
                                            minor_locator=False,
                                            plot_obj=subplot)
    minformatter = TimeSeries_DateFormatter(freq,
                                            dynamic_mode=True,
                                            minor_locator=True,
                                            plot_obj=subplot)
    subplot.xaxis.set_major_formatter(majformatter)
    subplot.xaxis.set_minor_formatter(minformatter)
    pylab.draw_if_interactive()
Пример #6
0
def tsplot(series, *args, **kwargs):
    """Plots the series to the current TimeSeries subplot.
    If the current plot is not a TimeSeriesPlot, a new TimeSeriesFigure is created."""
    # allow callers to override the hold state by passing hold=True|False
    b = pylab.ishold()
    h = kwargs.pop('hold', None)
    if h is not None:
        pylab.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, TimeSeriesFigure):
            fig = tsfigure(series=series)
    else:
        fig = tsfigure(series=series)
    # Get the current axe, or create one
    sub = fig._axstack()
    if sub is None:
        sub = fig.add_tsplot(111,series=series,**kwargs)
    try:
        ret = sub.tsplot(series, *args, **kwargs)
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return ret
Пример #7
0
def format_dateaxis(subplot, freq):
    """
    Pretty-formats the date axis (x-axis).

    Major and minor ticks are automatically set for the frequency of the
    current underlying series.  As the dynamic mode is activated by
    default, changing the limits of the x axis will intelligently change
    the positions of the ticks.
    """
    majlocator = TimeSeries_DateLocator(freq, dynamic_mode=True,
                                        minor_locator=False,
                                        plot_obj=subplot)
    minlocator = TimeSeries_DateLocator(freq, dynamic_mode=True,
                                        minor_locator=True,
                                        plot_obj=subplot)
    subplot.xaxis.set_major_locator(majlocator)
    subplot.xaxis.set_minor_locator(minlocator)

    majformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True,
                                            minor_locator=False,
                                            plot_obj=subplot)
    minformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True,
                                            minor_locator=True,
                                            plot_obj=subplot)
    subplot.xaxis.set_major_formatter(majformatter)
    subplot.xaxis.set_minor_formatter(minformatter)
    pylab.draw_if_interactive()
Пример #8
0
 def __init__(self, fig=None, rect=None, **kwargs):
     if fig is None:
         fig = pylab.gcf()
     if rect is None:
         rect = [.15, .15, .75, .75]
     super(myaxes, self).__init__(fig, rect, **kwargs)
     fig.add_axes(self)
     pylab.draw_if_interactive()
Пример #9
0
 def __init__(self,fig=None,rect=None,**kwargs):
     if fig is None:
         fig=pylab.gcf()
     if rect is None:
         rect=[.15,.15,.75,.75]
     super(myaxes,self).__init__(fig,rect,**kwargs)
     fig.add_axes(self)
     pylab.draw_if_interactive()
Пример #10
0
def add_yaxis(fsp=None, position='right', yscale=None, basey=10, subsy=None,
              **kwargs):
    """Adds a second y-axis to a plot.
 
:Parameters:
    `fsp` : Subplot *[None]*
        Subplot to which the secondary y-axis is added. If *None*, the current
        subplot is selected
    `position` : String in `('left','right')` *['right']*
        Position of the new axis.
    `yscale` : String, in `('log', 'linear')` *[None]*
        Scale of the new axis. If None, uses the same scale as the first y 
axis
    `basey` : Integer *[10]*
        Base of the logarithm for the new axis (if needed).
    `subsy` : sequence *[None]*
        Sequence of the location of the minor ticks;
        None defaults to autosubs, which depend on the number of decades in 
the plot.  
        Eg for base 10, subsy=(1,2,5) will  put minor ticks on 1,2,5,11,12,15, 
21, ....
        To turn off minor ticking, set subsy=[]
 
    """
    if fsp is None:
        fsp = pylab.gca()
    if not isinstance(fsp, TimeSeriesPlot):
        raise TypeError("The current plot is not a TimeSeriesPlot")
    fig = fsp.figure
    axisini = fsp.axis()
    fsp_alt_args = (fsp._rows, fsp._cols, fsp._num+1)
    fsp_alt = fig.add_tsplot(frameon=False, position=fsp.get_position(),
                             sharex=fsp, *fsp_alt_args)
    # Set position ....................
    if position == 'right':
        (inipos, newpos) = ('left', 'right')
    else:
        (inipos, newpos) = ('right','left')
    # Force scales tics to one side ...
    fsp.yaxis.set_ticks_position(inipos)
    fsp.yaxis.set_label_position(inipos)
    # Force 2nd ticks to the other side..
    fsp_alt.yaxis.set_ticks_position(newpos)
    fsp_alt.yaxis.set_label_position(newpos) 
    # Force period axis scale..........
    if yscale is None:
        yscale = fsp.get_yscale()
        try:
            basey = fsp.yaxis.get_major_locator()._base
        except AttributeError:
            basey = 10.
    fsp_alt.set_yscale(yscale, basey=basey, subsy=subsy)
    # Guess we're good ................
    fsp_alt.set_xticks('')
    fsp_alt.set_xticklabels('')
    
    pylab.draw_if_interactive()
    return fsp_alt
Пример #11
0
    def drawall(self, **kwargs):
        if not self.n == self.drawax.shape:
            self.drawax = np.ones(self.n, dtype='bool')
        if not self.n[1] == self.hrel.shape[0]:
            self.hrel = np.ones(self.n[1], dtype='float32')
        if not self.n[0] == self.vrel.shape[0]:
            self.vrel = np.ones(self.n[0], dtype='float32')
        if 'lw' in kwargs.keys():
            kwargs['linewidth'] = kwargs.pop('lw', self.linewidth)
        if 'linewidth' not in kwargs.keys():
            kwargs['linewidth'] = self.linewidth
        else:
            self.linewidth = kwargs['linewidth']

        forcesharex = False
        forcesharey = False
        if 'sharex' in kwargs.keys():
            forcesharex = True
        if 'sharey' in kwargs.keys():
            forcesharey = True
        inter = pylab.isinteractive()
        pylab.interactive(False)
                          # wait to draw the axes, until they've all been
                          # created.
        axg = self.axgrid()
        for iv in range(self.n[0]):
            for ih in range(self.n[1]):
                if forcesharex:  # I should put this functionality into a func.
                    pass
                elif (self.sharex[iv, ih] and
                      self._sharex_ax[self.sharex[iv, ih]]):
                    kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]]
                elif 'sharex' in kwargs.keys():
                    kwargs.pop('sharex')
                if forcesharey:
                    pass
                elif (self.sharey[iv, ih] and
                      self._sharey_ax[self.sharey[iv, ih]]):
                    kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]]
                elif 'sharey' in kwargs.keys():
                    kwargs.pop('sharey')
                if self.drawax[iv, ih]:
                    # self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs)
                    self.ax[iv, ih] = axes(axg[iv, ih,:], **kwargs)
                    self.ax[iv, ih].hold(True)
                    if self.sharex[iv, ih] and not\
                       self._sharex_ax[self.sharex[iv, ih]]:
                        self._sharex_ax[self.sharex[iv, ih]] = self.ax[iv, ih]
                    if self.sharey[iv, ih] and not\
                       self._sharey_ax[self.sharey[iv, ih]]:
                        self._sharey_ax[self.sharey[iv, ih]] = self.ax[iv, ih]
        self._xlabel_ax = self.ax[-1, 0]
        self._ylabel_ax = self._xlabel_ax
        pylab.interactive(inter)
        pylab.draw_if_interactive()
        return self.ax
def plot_dt(tri, colors=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if colors is None:
        colors = [(0,0,0,0.2)]
    lc = mpl.collections.LineCollection(np.array([((tri.x[i], tri.y[i]), (tri.x[j], tri.y[j]))
            for i, j in tri.edge_db]), colors=colors)
    ax = pl.gca()
    ax.add_collection(lc)
    pl.draw_if_interactive()
Пример #13
0
def plot_dt(tri, colors=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if colors is None:
        colors = [(0,0,0,0.2)]
    lc = mpl.collections.LineCollection(sp.array([((tri.x[i], tri.y[i]), (tri.x[j], tri.y[j]))
            for i, j in tri.edge_db]), colors=colors)
    ax = pl.gca()
    ax.add_collection(lc)
    pl.draw_if_interactive()
Пример #14
0
def plot_vo(tri, colors=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if colors is None:
        colors = [(0, 1, 0, 0.2)]
    lc = mpl.collections.LineCollection(np.array(
        [(tri.circumcenters[i], tri.circumcenters[j])
         for i in xrange(len(tri.circumcenters))
         for j in tri.triangle_neighbors[i] if j != -1]),
        colors=colors)
    ax = pl.gca()
    ax.add_collection(lc)
    pl.draw_if_interactive()
Пример #15
0
def plot_vo(tri, colors=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if colors is None:
        colors = [(0, 1, 0, 0.2)]
    lc = mpl.collections.LineCollection(np.array(
        [(tri.circumcenters[i], tri.circumcenters[j])
         for i in xrange(len(tri.circumcenters))
         for j in tri.triangle_neighbors[i] if j != -1]),
        colors=colors)
    ax = pl.gca()
    ax.add_collection(lc)
    pl.draw_if_interactive()
def plot_cc(tri, edgecolor=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if edgecolor is None:
        edgecolor = (0,0,1,0.2)
    dxy = (np.array([(tri.x[i], tri.y[i]) for i,j,k in tri.triangle_nodes])
        - tri.circumcenters)
    r = np.hypot(dxy[:,0], dxy[:,1])
    ax = pl.gca()
    for i in range(len(r)):
        p = mpl.patches.Circle(tri.circumcenters[i], r[i], resolution=100, edgecolor=edgecolor,
            facecolor=(1,1,1,0), linewidth=0.2)
        ax.add_patch(p)
    pl.draw_if_interactive()
Пример #17
0
def plot_cc(tri, edgecolor=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if edgecolor is None:
        edgecolor = (0,0,1,0.2)
    dxy = (sp.array([(tri.x[i], tri.y[i]) for i,j,k in tri.triangle_nodes])
        - tri.circumcenters)
    r = sp.hypot(dxy[:,0], dxy[:,1])
    ax = pl.gca()
    for i in xrange(len(r)):
        p = mpl.patches.Circle(tri.circumcenters[i], r[i], resolution=100, edgecolor=edgecolor,
            facecolor=(1,1,1,0), linewidth=0.2)
        ax.add_patch(p)
    pl.draw_if_interactive()
Пример #18
0
def format_dateaxis(subplot, freq, index):
    """
    Pretty-formats the date axis (x-axis).

    Major and minor ticks are automatically set for the frequency of the
    current underlying series.  As the dynamic mode is activated by
    default, changing the limits of the x axis will intelligently change
    the positions of the ticks.
    """
    from matplotlib import pylab

    # handle index specific formatting
    # Note: DatetimeIndex does not use this
    # interface. DatetimeIndex uses matplotlib.date directly
    if isinstance(index, ABCPeriodIndex):

        majlocator = TimeSeries_DateLocator(freq,
                                            dynamic_mode=True,
                                            minor_locator=False,
                                            plot_obj=subplot)
        minlocator = TimeSeries_DateLocator(freq,
                                            dynamic_mode=True,
                                            minor_locator=True,
                                            plot_obj=subplot)
        subplot.xaxis.set_major_locator(majlocator)
        subplot.xaxis.set_minor_locator(minlocator)

        majformatter = TimeSeries_DateFormatter(freq,
                                                dynamic_mode=True,
                                                minor_locator=False,
                                                plot_obj=subplot)
        minformatter = TimeSeries_DateFormatter(freq,
                                                dynamic_mode=True,
                                                minor_locator=True,
                                                plot_obj=subplot)
        subplot.xaxis.set_major_formatter(majformatter)
        subplot.xaxis.set_minor_formatter(minformatter)

        # x and y coord info
        subplot.format_coord = functools.partial(_format_coord, freq)

    elif isinstance(index, ABCTimedeltaIndex):
        subplot.xaxis.set_major_formatter(TimeSeries_TimedeltaFormatter())
    else:
        raise TypeError("index type not supported")

    pylab.draw_if_interactive()
Пример #19
0
def format_dateaxis(subplot, freq, index):
    """
    Pretty-formats the date axis (x-axis).

    Major and minor ticks are automatically set for the frequency of the
    current underlying series.  As the dynamic mode is activated by
    default, changing the limits of the x axis will intelligently change
    the positions of the ticks.
    """

    # handle index specific formatting
    # Note: DatetimeIndex does not use this
    # interface. DatetimeIndex uses matplotlib.date directly
    if isinstance(index, PeriodIndex):

        majlocator = TimeSeries_DateLocator(freq, dynamic_mode=True,
                                            minor_locator=False,
                                            plot_obj=subplot)
        minlocator = TimeSeries_DateLocator(freq, dynamic_mode=True,
                                            minor_locator=True,
                                            plot_obj=subplot)
        subplot.xaxis.set_major_locator(majlocator)
        subplot.xaxis.set_minor_locator(minlocator)

        majformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True,
                                                minor_locator=False,
                                                plot_obj=subplot)
        minformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True,
                                                minor_locator=True,
                                                plot_obj=subplot)
        subplot.xaxis.set_major_formatter(majformatter)
        subplot.xaxis.set_minor_formatter(minformatter)

        # x and y coord info
        subplot.format_coord = lambda t, y: (
            "t = {0}  y = {1:8f}".format(Period(ordinal=int(t), freq=freq), y))

    elif isinstance(index, TimedeltaIndex):
        subplot.xaxis.set_major_formatter(
            TimeSeries_TimedeltaFormatter())
    else:
        raise TypeError('index type not supported')

    pylab.draw_if_interactive()
Пример #20
0
def tsplot(series, *args, **kwargs):
    """
    Plots the series to the current :class:`TimeSeriesPlot`.
    If the current plot is not a :class:`TimeSeriesPlot`,
    a new :class:`TimeSeriesFigure` is created.

    Parameters
    ----------
    series : TimeSeries
        The time series to plot
    %(mandatoryplotargs)s
    kwargs : var
        Optional arguments for the creation of the subplot.
    """
    # allow callers to override the hold state by passing hold=True|False
    b = pylab.ishold()
    h = kwargs.pop('hold', None)
    if h is not None:
        pylab.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, TimeSeriesFigure):
            fig = tsfigure(series=series)
    else:
        fig = tsfigure(series=series)
    # Get the current axe, or create one
    sub = fig._axstack()
    if sub is None:
        sub = fig.add_tsplot(111, series=series, **kwargs)
    try:
        ret = sub.tsplot(series, *args, **kwargs)
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return ret
Пример #21
0
def tsplot(series, *args, **kwargs):
    """
    Plots the series to the current :class:`TimeSeriesPlot`.
    If the current plot is not a :class:`TimeSeriesPlot`,
    a new :class:`TimeSeriesFigure` is created.

    Parameters
    ----------
    series : TimeSeries
        The time series to plot
    %(mandatoryplotargs)s
    kwargs : var
        Optional arguments for the creation of the subplot.
    """
    # allow callers to override the hold state by passing hold=True|False
    b = pylab.ishold()
    h = kwargs.pop("hold", None)
    if h is not None:
        pylab.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, TimeSeriesFigure):
            fig = tsfigure(series=series)
    else:
        fig = tsfigure(series=series)
    # Get the current axe, or create one
    sub = fig._axstack()
    if sub is None:
        sub = fig.add_tsplot(111, series=series, **kwargs)
    try:
        ret = sub.tsplot(series, *args, **kwargs)
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return ret
Пример #22
0
def draw_networkx(G, pos, with_labels=True, **kwds):
    """Draw the graph G with given node positions pos

    Usage:

    >>> G=nx.dodecahedral_graph()
    >>> pos=nx.spring_layout(G)
    >>> nx.draw_networkx(G,pos)

    This is same as 'draw' but the node positions *must* be
    specified in the variable pos.
    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx.layout for functions that compute node positions.

    An optional matplotlib axis can be provided through the
    optional keyword ax.

    with_labels contols text labeling of the nodes

    Also see:

    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    """
    try:
        import matplotlib.pylab as pylab
    except ImportError:
        raise ImportError, "Matplotlib required for draw()"
    except RuntimeError:
        pass  # unable to open display

    node_collection = draw_networkx_nodes(G, pos, **kwds)
    edge_collection = draw_networkx_edges(G, pos, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #23
0
def draw_networkx(G, pos, with_labels=True, **kwds):
    """Draw the graph G with given node positions pos

    Usage:

    >>> G=nx.dodecahedral_graph()
    >>> pos=nx.spring_layout(G)
    >>> nx.draw_networkx(G,pos)

    This is same as 'draw' but the node positions *must* be
    specified in the variable pos.
    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx.layout for functions that compute node positions.

    An optional matplotlib axis can be provided through the
    optional keyword ax.

    with_labels contols text labeling of the nodes

    Also see:

    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    """
    try:
        import matplotlib.pylab as pylab
    except ImportError:
        raise ImportError, "Matplotlib required for draw()"
    except RuntimeError:
        pass  # unable to open display

    node_collection = draw_networkx_nodes(G, pos, **kwds)
    edge_collection = draw_networkx_edges(G, pos, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #24
0
def draw_networkx(G, pos=None, 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 networkx.layout for functions that compute node positions.
       
    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.  

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

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

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

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

    node_color: color string, or array of floats
       Node color. Can be a single color format string (default='r'),
       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. Can also be a
       dictionary keyed by node, and can be in any matplotlib acceptable
       color value.

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

    alpha: float
       The node transparency (default=1.0) 

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

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

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

    edge_color: color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       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
       Colormap for mapping intensities of edges (default=None)

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

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

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

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

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

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

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

    Notes
    -----
    Any keywords not listed above are passed through to draw_networkx_nodes(),
    draw_networkx_edges(), and draw_networkx_labels().  For finer control
    of drawing you can call those functions directly.

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

    >>> import pylab
    >>> limits=pylab.axis('off') # turn of axis 

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

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

    """
    try:
        import matplotlib.pylab as pylab
    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_patches=draw_networkx_nodes(G, pos, **kwds)
    edge_patches=draw_networkx_edges(G, pos, node_patches, **kwds) 
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #25
0
def draw(G, pos=None, ax=None, hold=None, **kwds):
    """Draw the graph G with Matplotlib (pylab).

    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.

    Good alternatives are:

    With pylab:

    >>> import pylab as P # 
    >>> import networkx as nx
    >>> G=nx.dodecahedral_graph()
    >>> nx.draw(G)  # networkx draw()
    >>> P.draw()    # pylab draw()
    
    With pyplot

    >>> 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.pylab as pylab
    except ImportError:
        raise ImportError, "Matplotlib required for draw()"
    except RuntimeError:
        print "Matplotlib unable to open display"
        raise

    cf=pylab.gcf()
    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
    b = pylab.ishold()
    h = kwds.pop('hold', None)
    if h is not None:
        pylab.hold(h)
    try:
        ax.set_axis_off()
        draw_networkx(G,pos=pos,ax=ax,**kwds)
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return
Пример #26
0
def draw_networkx(G, pos=None, 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 networkx.layout for functions that compute node positions.

    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='r')
       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 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

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

    >>> import pylab
    >>> limits=pylab.axis('off') # turn of axis

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

    See Also
    --------
    draw()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib.pylab as pylab
    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, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #27
0
 def plot(self,*args,**kwargs):
     # This just makes sure that my lines get drawn,
     # otherwise it just calls the axes' plot instance.
     super(myaxes,self).plot(*args,**kwargs)
     pylab.draw_if_interactive()
def draw(G, pos=None, ax=None, hold=None, **kwds):
    """Draw the graph G with Matplotlib (pylab).

    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.

    Good alternatives are:

    With pylab:

    >>> import pylab as P #
    >>> import networkx as nx
    >>> G=nx.dodecahedral_graph()
    >>> nx.draw(G)  # networkx draw()
    >>> P.draw()    # pylab draw()

    With pyplot

    >>> 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.pylab as pylab
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    cf=pylab.gcf()
    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
    b = pylab.ishold()
    h = kwds.pop('hold', None)
    if h is not None:
        pylab.hold(h)
    try:
        draw_networkx(G,pos=pos,ax=ax,**kwds)
        ax.set_axis_off()
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return
Пример #29
0
def axes(*args, **kwargs):
    """
    Add an axes at position rect specified by:

    - ``axes()`` by itself creates a default full ``subplot(111)`` window axis.

    - ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
      height] in normalized (0, 1) units.  *axisbg* is the background
      color for the axis, default white.

    - ``axes(h)`` where *h* is an axes instance makes *h* the current
      axis.  An :class:`~matplotlib.axes.Axes` instance is returned.

    =======   ============   ================================================
    kwarg     Accepts        Desctiption
    =======   ============   ================================================
    axisbg    color          the axes background color
    frameon   [True|False]   display the frame?
    sharex    otherax        current axes shares xaxis attribute with otherax
    sharey    otherax        current axes shares yaxis attribute with otherax
    polar     [True|False]   use a polar axes?
    =======   ============   ================================================

    Examples:

    * :file:`examples/pylab_examples/axes_demo.py` places custom axes.
    * :file:`examples/pylab_examples/shared_axis_demo.py` uses
      *sharex* and *sharey*.

    This was copied from the pyplot axes function. Several methods
    have been added to the axes.

    """

    nargs = len(args)
    if nargs == 0:
        args = [[.1, .1, .8, .8]]
    if nargs > 1:
        raise TypeError('Only one non keyword arg to axes allowed')
    arg = args[0]

    axd = {}
    newd = {}
    newd['lw'] = rcParams['axes.linewidth']
    try:
        axd['axisbg'] = kwargs.pop('axisbg')
    except:
        pass
    for nm in [
            'axisbg',
            'frameon',
            'sharex',
            'sharey',
            'polar',
    ]:
        if nm in kwargs.keys():
            axd[nm] = kwargs.pop(nm)
    if 'ticksize' in kwargs.keys():
        newd['xticksize'] = kwargs.get('ticksize')
        newd['yticksize'] = kwargs.pop('ticksize')
    for nm in [('lw', 'linewidth'), 'linewidth', 'xticksize', 'yticksize',
               ('fs', 'fontsize'), 'fontsize', 'xlocation', 'ylocation']:
        if nm.__class__ is tuple:
            ky = nm[0]
            nm = nm[1]
        else:
            ky = nm
            nm = nm
        if ky in kwargs:
            newd[nm] = kwargs.pop(ky)
    if ('fig' not in kwargs.keys()) and ('figure' not in kwargs.keys()):
        fig = pylab.gcf()
    elif 'figure' in kwargs.keys():
        fig = kwargs.pop('figure')
    else:
        fig = kwargs.pop('fig')

    if isinstance(arg, mpl.axes.Axes):
        a = fig.sca(arg)
    else:
        rect = arg
        a = fig.add_axes(rect, **axd)
        a.set(**kwargs)

        if 'xlocation' in newd.keys():
            a.xaxis.set_ticks_position(newd['xlocation'])
            if newd['xlocation'] == 'top':
                a.spines['bottom'].set_visible(False)
            elif newd['xlocation'] == 'bottom':
                a.spines['top'].set_visible(False)
        if 'ylocation' in newd.keys():
            a.yaxis.set_ticks_position(newd['ylocation'])
            if newd['ylocation'] == 'right':
                a.spines['left'].set_visible(False)
            elif newd['ylocation'] == 'left':
                a.spines['right'].set_visible(False)
        if 'lw' in newd.keys():
            for sp in a.spines:
                a.spines[sp].set_linewidth(newd['lw'])
            for tck in a.xaxis.get_ticklines():
                tck.set_mew(newd['lw'])
            for tck in a.yaxis.get_ticklines():
                tck.set_mew(newd['lw'])
        if 'xticksize' in newd.keys():
            for tck in a.xaxis.get_ticklines():
                tck.set_ms(newd['xticksize'])
        if 'yticksize' in newd.keys():
            for tck in a.yaxis.get_ticklines():
                tck.set_ms(newd['yticksize'])
        if 'fontsize' in newd.keys():
            for tklbl in a.xaxis.get_ticklabels():
                tklbl.set_fontsize(newd['fontsize'])
            for tklbl in a.yaxis.get_ticklabels():
                tklbl.set_fontsize(newd['fontsize'])

    a.transAxesXDataY = transforms.blended_transform_factory(
        a.transAxes, a.transData)
    a.transDataXAxesY = transforms.blended_transform_factory(
        a.transData, a.transAxes)

    a.shadex = new.instancemethod(bf.shadex, a, Axes)
    a.shadey = new.instancemethod(bf.shadey, a, Axes)
    a.setaxesframe = new.instancemethod(bf._setaxesframe, a, Axes)
    a.annoteCorner = new.instancemethod(bf.annoteCorner, a, Axes)
    a.offset_text = new.instancemethod(bf.offset_text, a, Axes)
    a.cpcolor = new.instancemethod(bf.cpcolor, a, Axes)
    a.labelax = new.instancemethod(bf.labelax, a, Axes)
    a.skip_ticklabels = new.instancemethod(skip_ticklabels, a, Axes)
    a.errorshadex = new.instancemethod(bf.errorshadex, a, Axes)
    # a.plot_specobj=new.instancemethod(plot_specobj,a,Axes)

    pylab.draw_if_interactive()
    return a
Пример #30
0
def add_yaxis(fsp=None, position="right", yscale=None, basey=10, subsy=None):
    """
    Adds a second y-axis to a :class:`Subplot`.
    This function can also be used as a method.

    Parameters
    ----------
    fsp : {None, Subplot}
        Subplot to which the secondary y-axis is added.
        If None, the current subplot is selected: in that case, it should be
        a valid :class:`Subplot`.
        When used as a :class:`Subplot` method, this parameter points
        automatically to the calling subplot.
    position : {string}
        Position of the new axis, as either ``'left'`` or ``'right'``.
    yscale : {string}
        Scale of the new axis, as either ``'log'``, ``'linear'`` or ``None``.
        If None, uses the same scale as the first y axis.
    basey : {integer}
        Base of the logarithm for the new axis (if needed).
    subsy : {sequence}
        Sequence of the location of the minor ticks;
        None defaults to autosubs, which depend on the number of decades in
        the plot.
        Eg for base 10, ``subsy=(1,2,5)`` will  put minor ticks on 1, 2, 5, 11,
        12,15, 21, ....
        To turn off minor ticking, set ``subsy=[]``.

    Raises
    ------
    TypeError
        If the selected subplot is not a valid :class:`Subplot` object.

    """
    if fsp is None:
        fsp = pylab.gca()

    fig = fsp.figure
    axisini = fsp.axis()
    fsp_alt_args = (fsp._rows, fsp._cols, fsp._num + 1)
    fsp_alt = fig.add_subplot(frameon=False, position=fsp.get_position(), sharex=fsp, *fsp_alt_args)
    # Set position ....................
    if position.lower() == "right":
        (inipos, newpos) = ("left", "right")
    else:
        (inipos, newpos) = ("right", "left")
    # Force scales tics to one side ...
    fsp.yaxis.set_ticks_position(inipos)
    fsp.yaxis.set_label_position(inipos)
    # Force 2nd ticks to the other side..
    fsp_alt.yaxis.set_ticks_position(newpos)
    fsp_alt.yaxis.set_label_position(newpos)
    # Force period axis scale..........
    if yscale is None:
        yscale = fsp.get_yscale()
        try:
            basey = fsp.yaxis.get_major_locator()._base
        except AttributeError:
            basey = 10.0
    fsp_alt.set_yscale(yscale, basey=basey, subsy=subsy)

    pylab.draw_if_interactive()
    return fsp_alt
Пример #31
0
def draw(G, pos=None, ax=None, hold=None, **kwds):
    """Draw the graph G with matplotlib (pylab).

    This is a pylab friendly function that will use the
    current pylab figure axes (e.g. subplot).

    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx.layout for functions that compute node positions.

    Usage:

    >>> from networkx import *
    >>> G=dodecahedral_graph()
    >>> draw(G)
    >>> pos=graphviz_layout(G)
    >>> draw(G,pos)
    >>> draw(G,pos=spring_layout(G))

    Also see doc/examples/draw_*

    :Parameters:

      - `nodelist`: list of nodes to be drawn (default=G.nodes())
      - `edgelist`: list of edges to be drawn (default=G.edges())
      - `node_size`: scalar or array of the same length as nodelist (default=300)
      - `node_color`: single color string or numeric/numarray array of floats (default='r')
      - `node_shape`: node shape (default='o'), or 'so^>v<dph8' see pylab.scatter
      - `alpha`: transparency (default=1.0) 
      - `cmap`: colormap for mapping intensities (default=None)
      - `vmin,vmax`: min and max for colormap scaling (default=None)
      - `width`: line width of edges (default =1.0)
      - `edge_color`: scalar or array (default='k')
      - `edge_cmap`: colormap for edge intensities (default=None) 
      - `edge_vmin,edge_vmax`: min and max for colormap edge scaling (default=None)
      - `style`: edge linestyle (default='solid') (solid|dashed|dotted,dashdot)
      - `labels`: dictionary keyed by node of text labels (default=None)
      - `font_size`: size for text labels (default=12)
      - `font_color`: (default='k')
      - `font_weight`: (default='normal')
      - `font_family`: (default='sans-serif')
      - `ax`: matplotlib axes instance

    for more see pylab.scatter

    NB: this has the same name as pylab.draw so beware when using

    >>> from networkx import *

    since you will overwrite the pylab.draw function.

    A good alternative is to use

    >>> import pylab as P
    >>> import networkx as NX
    >>> G=NX.dodecahedral_graph()

    and then use

    >>> NX.draw(G)  # networkx draw()

    and
    >>> P.draw()    # pylab draw()

    """
    try:
        import matplotlib.pylab as pylab
    except ImportError:
        raise ImportError, "Matplotlib required for draw()"
    except RuntimeError:
        pass # unable to open display

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

    cf=pylab.gcf()
    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
    b = pylab.ishold()
    h = kwds.pop('hold', None)
    if h is not None:
        pylab.hold(h)
    try:
        draw_networkx(G,pos,ax=ax,**kwds)
        ax.set_axis_off()
        pylab.draw_if_interactive()
    except:
        pylab.hold(b)
        raise
    pylab.hold(b)
    return
Пример #32
0
def axes(*args, **kwargs):
    """
    Add an axes at position rect specified by:

    - ``axes()`` by itself creates a default full ``subplot(111)`` window axis.

    - ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
      height] in normalized (0, 1) units.  *axisbg* is the background
      color for the axis, default white.

    - ``axes(h)`` where *h* is an axes instance makes *h* the current
      axis.  An :class:`~matplotlib.axes.Axes` instance is returned.

    =======   ============   ================================================
    kwarg     Accepts        Desctiption
    =======   ============   ================================================
    axisbg    color          the axes background color
    frameon   [True|False]   display the frame?
    sharex    otherax        current axes shares xaxis attribute with otherax
    sharey    otherax        current axes shares yaxis attribute with otherax
    polar     [True|False]   use a polar axes?
    =======   ============   ================================================

    Examples:

    * :file:`examples/pylab_examples/axes_demo.py` places custom axes.
    * :file:`examples/pylab_examples/shared_axis_demo.py` uses
      *sharex* and *sharey*.
      
      This was copied from the pyplot axes function

    """

    nargs = len(args)
    if nargs==0:
        args=[[.1,.1,.8,.8]]
    if nargs>1:
        raise TypeError('Only one non keyword arg to axes allowed')
    arg = args[0]

    axd={}
    newd={}
    newd['lw']=rcParams['axes.linewidth']
    if kwargs.has_key('axisbg'):
        axd['axisbg']=kwargs.pop('axisbg')
    if kwargs.has_key('frameon'):
        axd['frameon']=kwargs.pop('frameon')
    if kwargs.has_key('sharex'):
        axd['sharex']=kwargs.pop('sharex')
    if kwargs.has_key('sharey'):
        axd['sharey']=kwargs.pop('sharey')
    if kwargs.has_key('polar'):
        axd['polar']=kwargs.pop('polar')
    if kwargs.has_key('linewidth'):
        newd['lw']=kwargs.pop('linewidth')
    if kwargs.has_key('lw'):
        newd['lw']=kwargs.pop('lw')
    if kwargs.has_key('ticksize'):
        newd['xticksize']=kwargs.get('ticksize')
        newd['yticksize']=kwargs.pop('ticksize')
    if kwargs.has_key('xticksize'):
        newd['xticksize']=kwargs.pop('xticksize')
    if kwargs.has_key('yticksize'):
        newd['yticksize']=kwargs.pop('yticksize')
    if kwargs.has_key('fs'):
        newd['fontsize']=kwargs.pop('fs')
    if kwargs.has_key('fontsize'):
        newd['fontsize']=kwargs.pop('fontsize')
    if kwargs.has_key('xlocation'):
        newd['xlocation']=kwargs.pop('xlocation')
    if kwargs.has_key('ylocation'):
        newd['ylocation']=kwargs.pop('ylocation')
    if (not kwargs.has_key('fig')) and (not kwargs.has_key('figure')):
        fig=pylab.gcf()
    elif kwargs.has_key('figure'):
        fig=kwargs.pop('figure')
    else:
        fig=kwargs.pop('fig')

    if isinstance(arg, mpl.axes.Axes):
        a = fig.sca(arg)
    else:
        rect = arg
        a = fig.add_axes(rect, **axd)
        a.set(**kwargs)
        
        if newd.has_key('xlocation'):
            a.xaxis.set_ticks_position(newd['xlocation'])
            if newd['xlocation']=='top':
                a.spines['bottom'].set_visible(False)
            elif newd['xlocation']=='bottom':
                a.spines['top'].set_visible(False)
        if newd.has_key('ylocation'):
            a.yaxis.set_ticks_position(newd['ylocation'])
            if newd['ylocation']=='right':
                a.spines['left'].set_visible(False)
            elif newd['ylocation']=='left':
                a.spines['right'].set_visible(False)
        if newd.has_key('lw'):
            for sp in a.spines:
                a.spines[sp].set_linewidth(newd['lw'])
            for tck in a.xaxis.get_ticklines():
                tck.set_mew(newd['lw'])
            for tck in a.yaxis.get_ticklines():
                tck.set_mew(newd['lw'])
        if newd.has_key('xticksize'):
            for tck in a.xaxis.get_ticklines():
                tck.set_ms(newd['xticksize'])
        if newd.has_key('yticksize'):
            for tck in a.yaxis.get_ticklines():
                tck.set_ms(newd['yticksize'])
        if newd.has_key('fontsize'):
            for tklbl in a.xaxis.get_ticklabels():
                tklbl.set_fontsize(newd['fontsize'])
            for tklbl in a.yaxis.get_ticklabels():
                tklbl.set_fontsize(newd['fontsize'])

    a.transAxesXDataY=transforms.blended_transform_factory(a.transAxes,a.transData)
    a.transDataXAxesY=transforms.blended_transform_factory(a.transData,a.transAxes)

    a.hln=new.instancemethod(_hln,a,Axes)
    a.vln=new.instancemethod(_vln,a,Axes)
    a.shadex=new.instancemethod(shadex,a,Axes)
    a.shadey=new.instancemethod(shadey,a,Axes)
    a.setaxesframe=new.instancemethod(_setaxesframe,a,Axes)
    a.annoteCorner=new.instancemethod(annoteCorner,a,Axes)
    a.offset_text=new.instancemethod(offset_text,a,Axes)
    a.cpcolor=new.instancemethod(cpcolor,a,Axes)
    a.cbar=new.instancemethod(cbar,a,Axes)
    a.labelax=new.instancemethod(labelax,a,Axes)
    a.skip_ticklabels=new.instancemethod(skip_ticklabels,a,Axes)
    a.errorshadex=new.instancemethod(errorshadex,a,Axes)
    #a.plot_specobj=new.instancemethod(plot_specobj,a,Axes)
    
    pylab.draw_if_interactive()
    return a
Пример #33
0
def add_yaxis(fsp=None, position='right', yscale=None, basey=10, subsy=None):
    """
    Adds a second y-axis to a :class:`TimeSeriesPlot`.
    This function can also be used as a method.

    Parameters
    ----------
    fsp : {None, TimeSeriesPlot}
        Subplot to which the secondary y-axis is added.
        If None, the current subplot is selected: in that case, it should be
        a valid :class:`TimeSeriesPlot`.
        When used as a :class:`TimeSeriesPlot` method, this parameter points
        automatically to the calling subplot.
    position : {string}
        Position of the new axis, as either ``'left'`` or ``'right'``.
    yscale : {string}
        Scale of the new axis, as either ``'log'``, ``'linear'`` or ``None``.
        If None, uses the same scale as the first y axis.
    basey : {integer}
        Base of the logarithm for the new axis (if needed).
    subsy : {sequence}
        Sequence of the location of the minor ticks;
        None defaults to autosubs, which depend on the number of decades in
        the plot.
        Eg for base 10, ``subsy=(1,2,5)`` will  put minor ticks on 1, 2, 5, 11,
        12,15, 21, ....
        To turn off minor ticking, set ``subsy=[]``.

    Raises
    ------
    TypeError
        If the selected subplot is not a valid :class:`TimeSeriesPlot` object.

    """
    if fsp is None:
        fsp = pylab.gca()
    if not isinstance(fsp, TimeSeriesPlot):
        raise TypeError("The current plot is not a TimeSeriesPlot")
    fig = fsp.figure
    axisini = fsp.axis()
    fsp_alt_args = (fsp._rows, fsp._cols, fsp._num + 1)
    fsp_alt = fig.add_tsplot(frameon=False,
                             position=fsp.get_position(),
                             sharex=fsp,
                             *fsp_alt_args)
    # Set position ....................
    if position.lower() == 'right':
        (inipos, newpos) = ('left', 'right')
    else:
        (inipos, newpos) = ('right', 'left')
    # Force scales tics to one side ...
    fsp.yaxis.set_ticks_position(inipos)
    fsp.yaxis.set_label_position(inipos)
    # Force 2nd ticks to the other side..
    fsp_alt.yaxis.set_ticks_position(newpos)
    fsp_alt.yaxis.set_label_position(newpos)
    # Force period axis scale..........
    if yscale is None:
        yscale = fsp.get_yscale()
        try:
            basey = fsp.yaxis.get_major_locator()._base
        except AttributeError:
            basey = 10.
    fsp_alt.set_yscale(yscale, basey=basey, subsy=subsy)

    pylab.draw_if_interactive()
    return fsp_alt
def draw_networkx(G, pos=None, 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 networkx.layout for functions that compute node positions.

    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='r')
       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 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 (deafult='solid')
       Edge line style (solid|dashed|dotted,dashdot)

    labels : dictionary, optional (deafult=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

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

    >>> import pylab
    >>> limits=pylab.axis('off') # turn of axis

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

    See Also
    --------
    draw()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib.pylab as pylab
    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, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #35
0
def draw_networkx(G, pos=None, 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 networkx.layout for functions that compute node positions.
       
    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.  

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

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

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

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

    node_color: color string, or array of floats
       Node color. Can be a single color format string (default='r'),
       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. Can also be a
       dictionary keyed by node, and can be in any matplotlib acceptable
       color value.

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

    alpha: float
       The node transparency (default=1.0) 

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

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

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

    edge_color: color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       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
       Colormap for mapping intensities of edges (default=None)

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

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

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

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

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

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

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

    Notes
    -----
    Any keywords not listed above are passed through to draw_networkx_nodes(),
    draw_networkx_edges(), and draw_networkx_labels().  For finer control
    of drawing you can call those functions directly.

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

    >>> import pylab
    >>> limits=pylab.axis('off') # turn of axis 

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

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

    """
    try:
        import matplotlib.pylab as pylab
    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_patches = draw_networkx_nodes(G, pos, **kwds)
    edge_patches = draw_networkx_edges(G, pos, node_patches, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    pylab.draw_if_interactive()
Пример #36
0
 def plot(self, *args, **kwargs):
     # This just makes sure that my lines get drawn,
     # otherwise it just calls the axes' plot instance.
     super(myaxes, self).plot(*args, **kwargs)
     pylab.draw_if_interactive()