Ejemplo n.º 1
0
def axes(*args, **kwargs):
    """
    Add an axes at positon 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 Axes instance is returned
    """

    nargs = len(args)
    if len(args)==0: return subplot(111, **kwargs)
    if nargs>1:
        error_msg('Only one non keyword arg to axes allowed')
        return
    
    arg = args[0]

    if isinstance(arg, Axes):
        get_current_fig_manager().set_current_axes(arg)
        ret = arg
    else:
        rect = arg
        ret = get_current_fig_manager().add_axes(rect, **kwargs)
    draw_if_interactive()
    return ret
Ejemplo n.º 2
0
 def wrapper(*args, **kwargs):
     try:
         func = getattr(gca(), name)
         ret =  func(*args, **kwargs)
     except ValueError, msg:
         msg = raise_msg_to_str(msg)
         error_msg(msg)
Ejemplo n.º 3
0
def subplot(*args, **kwargs):
    """
    Create a subplot command, creating axes with

      subplot(numRows, numCols, plotNum)

    where plotNum=1 is the first plot number and increasing plotNums
    fill rows first.  max(plotNum)==numRows*numCols

    You can leave out the commas if numRows<=numCols<=plotNum<10, as
    in

      subplot(211)    # 2 rows, 1 column, first (upper) plot

    subplot(111) is the default axis

    The background color of the subplot can be specified via keyword
    argument 'axisbg', which takes a color string or gdk.Color as value, as in

    subplot(211, axisbg='y')
    """
    try:
        get_current_fig_manager().add_subplot(*args, **kwargs)
        a =  gca()
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Ejemplo n.º 4
0
def axis(*v):
    """\
Set/Get the axis properties::

    axis()  returns the current axis as a length a length 4 vector

    axis(v) where v = [xmin, xmax, ymin, ymax] sets the min and max of the x
        and y axis limits

    axis('off') turns off the axis lines and labels

    axis('equal') sets the xlim width and ylim height to be to be
        identical.  The longer of the two intervals is chosen
 
"""
    
    if len(v)==1 and is_string_like(v[0]):
        s = v[0]
        if s.lower()=='on': gca().set_axis_on()
        elif s.lower()=='off': gca().set_axis_off()
        elif s.lower()=='equal':
            ax = gca()
            xmin, xmax = ax.get_xlim()
            ymin, ymax = ax.get_ylim()
            
            width = xmax-xmin
            height = ymax-ymin
            # TODO: handle decreasing lim
            
            interval = max([width, height])
            ax.set_xlim((xmin, xmin+interval))
            ax.set_ylim((ymin, ymin+interval))            
            draw_if_interactive()
            
        else:
            error_msg('Unrecognized string %s to axis; try on or off' % s)
        return
    
    try: v[0]
    except IndexError:
        xlim = gca().get_xlim()
        ylim = gca().get_ylim()
        return [xlim[0], xlim[1], ylim[0], ylim[1]]
    
    v = v[0]
    if len(v) != 4:
        error_msg('v must contain [xmin xmax ymin ymax]')
        return 
    gca().set_xlim([v[0], v[1]])
    gca().set_ylim([v[2], v[3]])
    draw_if_interactive()
Ejemplo n.º 5
0
def _get_target_images(target=None):
    if target is None:
        ax = gca()
        all = ax.get_images()

        if not len(all):
            error_msg('You must first define an image, eg with imshow')
            return

        images = [all[-1]]
    else:
        if iterable(target): images = target
        else: images = [target]

    return images
Ejemplo n.º 6
0
def colorbar(tickfmt='%1.1f'):
    """
    Create a colorbar for current mappable image (see gci)

    tickfmt is a format string to format the colorbar ticks

    return value is the colorbar axes instance
    """

    mappable = gci()
    if mappable is None:
        error_msg('First define a mappable image (eg imshow, figimage, pcolor, scatter')
        return

    if isinstance(mappable, image.FigureImage):
        error_msg('Colorbars for figure images currently not supported')
        return
        
    ax = gca()

    cmap = mappable.cmap
    norm = mappable.norm
    
    if norm.vmin is None or norm.vmax is None:
        mappable.autoscale()
    cmin = norm.vmin
    cmax = norm.vmax
    l,b,w,h = ax.get_position()

    neww = 0.8*w
    ax.set_position((l,b,neww,h))
    cax = axes([l + 0.9*w, b, 0.1*w, h])
    N = 200
    c = linspace(cmin, cmax, N)
    C = array([c,c])

    coll = cax.imshow(transpose(C), interpolation='nearest',
                      origin='lower',
                      cmap=cmap, norm=norm,
                      extent=(0, 1, cmin, cmax))
    mappable.add_observer(coll)
    
    cax.set_xticks([])
    cax.yaxis.tick_right()

    # restore the current axes
    axes(ax)
    return cax
Ejemplo n.º 7
0
def figure(num=1,
           figsize   = None, # defaults to rc figure.figsize
           dpi       = None, # defaults to rc figure.dpi
           facecolor = None, # defaults to rc figure.facecolor
           edgecolor = None, # defaults to rc figure.edgecolor
           frameon = True,
           ):
    """
    figure(num = 1, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')


    Create a new figure and return a handle to it

    If figure(num) already exists, make it active and return the
    handle to it.

      figure(1)

    figsize - width in height x inches; defaults to rc figure.figsize
    dpi     - resolution; defaults to rc figure.dpi
    facecolor - the background color; defaults to rc figure.facecolor
    edgecolor - the border color; defaults to rc figure.edgecolor

    rcParams gives the default values from the .matplotlibrc file

    """

    if figsize is None   : figsize   = rcParams['figure.figsize']
    if dpi is None       : dpi       = rcParams['figure.dpi']
    if facecolor is None : facecolor = rcParams['figure.facecolor']
    if edgecolor is None : edgecolor = rcParams['figure.edgecolor']


    if num==0:
        error_msg('Figure number can not be 0.\n' + \
                  'Hey, give me a break, this is matlab compatability')

    figManager = _matlab_helpers.Gcf.get_fig_manager(num)
    if figManager is None:
        if get_backend()=='PS':  dpi = 72
        figManager = new_figure_manager(num, figsize, dpi, facecolor, edgecolor, frameon)
        _matlab_helpers.Gcf.set_active(figManager)
    
    return figManager.canvas.figure
Ejemplo n.º 8
0
def set(h, *args, **kwargs):
    """
    Set handle h property in string s to value val

    h can be a handle or vector of handles.

    h is an instance (or vector of instances) of a class, eg a Line2D
    or an Axes or Text.

    args is a list of string, value pairs.  if the string
    is 'somename', set function calls

      o.set_somename(value)

    for every instance in h.

    
    """

    if not iterable(h): h = [h]
    else: h = flatten(h)

    if len(args)%2:
        error_msg('The set args must be string, value pairs')

    funcvals = []
    for i in range(0, len(args)-1, 2):
        funcvals.append((args[i], args[i+1]))
    funcvals.extend(kwargs.items())

    ret = []
    for o in h:
        for s, val in funcvals:
            s = s.lower()
            funcName = "set_%s"%s
            func = getattr(o,funcName)        
            try: ret.extend( [func(val)] )
            except ValueError, msg:
                msg = exception_to_str(msg)
                error_msg(msg)
                raise RuntimeError(msg)
Ejemplo n.º 9
0
def clim(vmin=None, vmax=None):
    """
    Set the color limits of the current image

    To apply clim to all axes images do

    clim(0, 0.5)

    If either vmin or vmax is None, the image min/max respectively
    will be used for color scaling.

    If you want to set the clim of multiple images,
    use, for example for im in gca().get_images(): im.set_clim(0,
    0.05)
    
    """  
    im = gci._current
    if im is None:
        error_msg('You must first define an image, eg with imshow')
        return
    im.set_clim(vmin, vmax)
    draw_if_interactive()
Ejemplo n.º 10
0
def specgram(*args, **kwargs):
    try: ret =  gca().specgram(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
Ejemplo n.º 11
0
def pcolor(*args, **kwargs):
    try:
        ret =  gca().pcolor(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
Ejemplo n.º 12
0
def imshow(*args, **kwargs):
    try: im =  gca().imshow(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError(msg)
Ejemplo n.º 13
0
def figimage(*args, **kwargs):    
    try: ret =  gcf().figimage(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError(msg)
Ejemplo n.º 14
0
def figtext(*args, **kwargs):    
    try: ret =  gcf().text(*args, **kwargs)
    except RuntimeError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError(msg)
Ejemplo n.º 15
0
        error_msg(msg)
        raise RuntimeError(msg)
    else:
        draw_if_interactive()
        return ret
figtext.__doc__ = Figure.text.__doc__

def figimage(*args, **kwargs):    
    try: ret =  gcf().figimage(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError(msg)
    except RuntimeError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError(msg)
    draw_if_interactive()
    gci._current = ret
    return ret
figimage.__doc__ = Figure.figimage.__doc__
    
def figlegend(handles, labels, loc):
    """
    Place a legend in the figure.  Labels are a sequence of
    strings, handles is a sequence of line or patch instances, and
    loc can be a string or an integer specifying the legend
    location

    USAGE: 
      legend( (line1, line2, line3),