Esempio n. 1
0
    def draw_image(self, x, y, im, origin, bbox):
        if bbox != None:
            l, b, w, h = bbox.get_bounds()
            #rectangle = (int(l), self.height-int(b+h),
            #             int(w), int(h))
            # set clip rect?

        flipud = origin == 'lower'
        rows, cols, s = im.as_str(flipud)

        X = fromstring(s, UInt8)
        X.shape = rows, cols, 4

        pb = gtk.gdk.Pixbuf(
            gtk.gdk.COLORSPACE_RGB,
            #has_alpha=1, bits_per_sample=8,
            has_alpha=True,
            bits_per_sample=8,
            width=cols,
            height=rows)
        try:
            pa = pb.get_pixels_array()
        except AttributeError:
            pa = pb.pixel_array
        except RuntimeError, exc:  #  pygtk was not compiled with Numeric Python support
            verbose.report_error('Error: %s' % exc)
            return
Esempio n. 2
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath=False):
        """
        Render the matplotlib.text.Text instance at x, y in window
        coords using GraphicsContext gc
        """
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()
        ctx = gc.ctx

        if ismath:
            verbose.report_error('Mathtext not implemented yet')
        else:
            # text is looking too small - size, scale problem?
            ctx.new_path()
            ctx.move_to(x, y)
            ctx.select_font(prop.get_name(), self.fontangles[prop.get_style()],
                            self.fontweights[prop.get_weight()])
            scale = self.get_text_scale()
            size = prop.get_size_in_points()

            ctx.save()
            if angle:
                ctx.rotate(-angle * pi / 180)
            ctx.scale_font(scale * size)
            ctx.show_text(s)
            ctx.restore()
Esempio n. 3
0
def print_figure_fn(figure, filename, dpi=150, facecolor='w', edgecolor='w',
                    orientation='portrait'):
    if DEBUG: print 'backend_cairo.FigureCanvasCairo.%s()' % _fn_name()

    # settings for printing
    figure.dpi.set(dpi)
    figure.set_facecolor(facecolor)
    figure.set_edgecolor(edgecolor)        

    if isinstance(filename, file):   # eg when do savefig(sys.stdout)
        _save_png (figure, filename) # assume PNG format
    else:
        root, ext = os.path.splitext(filename)       
        ext = ext[1:]
        if ext == '':
            ext      = IMAGE_FORMAT_DEFAULT
            filename = filename + '.' + ext

        ext = ext.lower()
        if ext in ('png', 'ps'):  # native formats
            try:
                fileObject = file(filename,'wb')
            except IOError, exc:
                verbose.report_error("%s: %s" % (exc.filename, exc.strerror))
            else:
                if ext == 'png': _save_png (figure, fileObject)
                else:            _save_ps  (figure, fileObject, orientation)
            
        elif ext in ('eps', 'svg'): # backend_svg/ps
            if ext == 'svg':
                from backend_svg import FigureCanvasSVG as FigureCanvas
            else:
                from backend_ps import FigureCanvasPS  as FigureCanvas
            fc = FigureCanvas(figure)
            fc.print_figure(filename, dpi, facecolor, edgecolor, orientation)
Esempio n. 4
0
    def _draw_rotated_text(self, gc, x, y, s, prop, angle):
        """
        Draw the text rotated 90 degrees
        """

        gdrawable = self.gdkDrawable
        ggc = gc.gdkGC

        layout = self._get_pango_layout(s, prop)
        inkRect, logicalRect = layout.get_pixel_extents()
        rect = inkRect
        l, b, w, h = rect

        x = int(x-h)
        y = int(y-w)
        # get the background image

        # todo: cache rotation for dynamic redraw until pygtk mem leak
        # fixed
        key = (x,y,s,angle,hash(prop))
        imageOut = self.rotated.get(key)
        if imageOut != None:
            gdrawable.draw_image(ggc, imageOut, 0, 0, x, y, h, w)
            return

        # save the background
        imageBack = gdrawable.get_image(x, y, w, h)
        imageVert = gdrawable.get_image(x, y, h, w)

        # transform the vertical image, write it onto the renderer,
        # and draw the layout onto it
        imageFlip = gtk.gdk.Image(type=gdk.IMAGE_NORMAL,
                                  visual=gdrawable.get_visual(),
                                  width=w, height=h)
        if imageFlip == None or imageBack == None or imageVert == None:
            verbose.report_error("Could not renderer vertical text", s)
            return
        imageFlip.set_colormap(gdrawable.get_colormap())
        for i in range(w):
            for j in range(h):
                imageFlip.put_pixel(i, j, imageVert.get_pixel(j,w-i-1) )

        gdrawable.draw_image(ggc, imageFlip, 0, 0, x, y, w, h)
        gdrawable.draw_layout(ggc, x, y-b, layout)

        # now get that image and flip it vertical
        imageIn = gdrawable.get_image(x, y, w, h)
        imageOut = gtk.gdk.Image(type=gdk.IMAGE_NORMAL,
                                 visual=gdrawable.get_visual(),
                                 width=h, height=w)
        imageOut.set_colormap(gdrawable.get_colormap())
        for i in range(w):
            for j in range(h):
                imageOut.put_pixel(j, i, imageIn.get_pixel(w-i-1,j) )

        # draw the old background and the flipped text
        gdrawable.draw_image(ggc, imageBack, 0, 0, x, y, w, h)
        gdrawable.draw_image(ggc, imageOut, 0, 0, x, y, h, w)
        self.rotated[key] = imageOut
        return True
Esempio n. 5
0
def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none,
           window=window_hanning, noverlap=0):
    """
    cohere the coherence between x and y.  Coherence is the normalized
    cross spectral density

    Cxy = |Pxy|^2/(Pxx*Pyy)

    The return value is (Cxy, f), where f are the frequencies of the
    coherence vector.  See the docs for psd and csd for information
    about the function arguments NFFT, detrend, windowm noverlap, as
    well as the methods used to compute Pxy, Pxx and Pyy.

    Returns the tuple Cxy, freqs

    """
    
    if len(x)<2*NFFT:
       verbose.report_error('Coherence is calculated by averaging over NFFT length segments.  Your signal is too short for your choice of NFFT')
    Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap)
    Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap)
    Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap)

    Cxy = divide(absolute(Pxy)**2, Pxx*Pyy)
    Cxy.shape = len(f),
    return Cxy, f
Esempio n. 6
0
def quotes_historical_yahoo(ticker, date1, date2):

    """
    Get historical data for ticker between date1 and date2.  date1 and
    date2 are datetime instances
    
    results are a list of

    d, open, close, high, low, volume
    
    where d is a floating poing representation of date, as returned by date2num
    """


    d1 = (date1.month-1, date1.day, date1.year)
    d2 = (date2.month-1, date2.day, date2.year)    


    urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=d&ignore=.csv'
    url =  urlFmt % (d1[0], d1[1], d1[2],
                     d2[0], d2[1], d2[2], ticker)

    ticker = ticker.upper()

    results = []
    try:
        lines = urlopen(url).readlines()
    except IOError, exc:
        verbose.report_error('urlopen() failure\n' + url + '\n' + exc.strerror[1])
        return None
Esempio n. 7
0
    def get_locator(self, d):
        'pick the best locator based on a distance'
        d = abs(d)
        if d <= 0:
            locator = MultipleLocator(0.2)
        else:

            try:
                ld = math.log10(d)
            except OverflowError:
                verbose.report_error(
                    'AutoLocator illegal dataInterval range %s; returning NullLocator'
                    % d)
                return NullLocator()

            fld = math.floor(ld)
            base = 10**fld

            #if ld==fld:  base = 10**(fld-1)
            #else:        base = 10**fld

            if d >= 5 * base: ticksize = base
            elif d >= 2 * base: ticksize = base / 2.0
            else: ticksize = base / 5.0
            #print 'base, ticksize, d', base, ticksize, d, self.viewInterval

            #print self.dataInterval, d, ticksize
            locator = MultipleLocator(ticksize)

        locator.set_view_interval(self.viewInterval)
        locator.set_data_interval(self.dataInterval)
        return locator
Esempio n. 8
0
def error_msg_template(msg, *args):
    """
    Signal an error condition.
    - in a GUI backend, popup a error dialog.
    - in a non-GUI backend delete this function and use
    'from matplotlib.backend_bases import error_msg'
    """
    verbose.report_error(msg)
    raise SystemExit
Esempio n. 9
0
 def set_capstyle(self, cs):
     """
     Set the capstyle as a string in ('butt', 'round', 'projecting')
     """
     if cs in ('butt', 'round', 'projecting'):
         self._capstyle = cs
         self.ctx.set_line_cap(self._capd[cs])
     else:
         verbose.report_error('Unrecognized cap style.  Found %s' % cs)
Esempio n. 10
0
 def set_joinstyle(self, js):
     """
     Set the join style to be one of ('miter', 'round', 'bevel')
     """
     if js in ('miter', 'round', 'bevel'):
         self._joinstyle = js
         self.ctx.set_line_join(self._joind[js])
     else:
         verbose.report_error('Unrecognized join style.  Found %s' % js)
Esempio n. 11
0
    def color(self, c):
        """
Set the color(s) of the line collection.  c can be a matplotlib color arg
(all patches have same color), or a a sequence or rgba tuples; if it
is a sequence the patches will cycle through the sequence

ACCEPTS: matplotlib color arg or sequence of rgba tuples"""
        verbose.report_error(
            'LineCollection.color deprecated; use set_color instead')
        return self.set_color(c)
Esempio n. 12
0
 def _get_font(self, prop):
     key = hash(prop)
     font = _fontd.get(key)
     if font is None:
         fname = fontManager.findfont(prop)
         try:
             font = FT2Font(str(fname))
         except RuntimeError, msg:
             verbose.report_error('Could not load filename for text "%s"'%fname)
             return None
         else:
             _fontd[key] = font
Esempio n. 13
0
    def draw_image(self, x, y, im, origin, bbox):
        """
        Draw the Image instance into the current axes; x is the
        distance in pixels from the left hand side of the canvas. y is
        the distance from the origin.  That is, if origin is upper, y
        is the distance from top.  If origin is lower, y is the
        distance from bottom

        origin is 'upper' or 'lower'

        bbox is a matplotlib.transforms.BBox instance for clipping, or
        None
        """
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()

        try:
            import cairo.numpy
        except:
            verbose.report_error(
                "cairo.numpy module required for draw_image()")
            return

        # bbox - not used
        flipud = origin == 'lower'

        ctx = cairo.Context()
        ctx.set_target_surface(self.surface)
        ctx.set_matrix(self.matrix)

        rows, cols, buffer = im.buffer_argb32(
        )  # ARGB32, but colors still wrong
        X = fromstring(buffer, UInt8)
        X.shape = rows, cols, 4
        #print dir(im)
        #print 'im.get_size()', im.get_size()
        #print 'r,c', rows, cols

        # GTK method
        #rows, cols, s = im.as_str(flipud) # RGBA
        #print 'r,c', rows, cols
        #X = fromstring(s, UInt8)
        #X.shape = rows, cols, 4

        # ARGB32
        surface = cairo.numpy.surface_create_for_array(X)

        # Alternative
        #surface = cairo.surface_create_for_image(buffer, cairo.FORMAT_ARGB32, cols, rows) #, stride)
        # error: TypeError: Cannot use string as modifiable buffer

        ctx.translate(x, y)
        ctx.show_surface(surface, cols, rows)
Esempio n. 14
0
    def _draw_rotated_text(self, gc, x, y, s, prop, angle):
        """
        Draw the text rotated 90 degrees, other angles are not supported
        """
        # this function (and its called functions) is a bottleneck
        # Pango 1.6 supports rotated text, but pygtk 2.4.0 does not yet have wrapper functions
        # GTK+ 2.6 pixbufs support rotation

        gdrawable = self.gdkDrawable
        ggc = gc.gdkGC

        layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
        l, b, w, h = inkRect
        x = int(x - h)
        y = int(y - w)

        if x < 0 or y < 0:  # window has shrunk and text is off the edge
            return

        key = (x, y, s, angle, hash(prop))
        imageVert = self.rotated.get(key)
        if imageVert != None:
            gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w)
            return

        imageBack = gdrawable.get_image(x, y, w, h)
        imageVert = gdrawable.get_image(x, y, h, w)
        #imageFlip = gtk.gdk.Image(type=gdk.IMAGE_NORMAL,
        imageFlip = gtk.gdk.Image(type=gdk.IMAGE_FASTEST,
                                  visual=gdrawable.get_visual(),
                                  width=w,
                                  height=h)
        if imageFlip == None or imageBack == None or imageVert == None:
            verbose.report_error("Could not renderer vertical text")
            return
        imageFlip.set_colormap(self._cmap)
        for i in range(w):
            for j in range(h):
                imageFlip.put_pixel(i, j, imageVert.get_pixel(j, w - i - 1))

        gdrawable.draw_image(ggc, imageFlip, 0, 0, x, y, w, h)
        gdrawable.draw_layout(ggc, x, y - b, layout)

        imageIn = gdrawable.get_image(x, y, w, h)
        for i in range(w):
            for j in range(h):
                imageVert.put_pixel(j, i, imageIn.get_pixel(w - i - 1, j))

        gdrawable.draw_image(ggc, imageBack, 0, 0, x, y, w, h)
        gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w)
        self.rotated[key] = imageVert
Esempio n. 15
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath):
        x, y = int(x), int(y)

        if angle not in (0,90):
            verbose.report_error('The GTK backend cannot draw text at a %i degree angle, try GtkAgg instead' % angle)

        elif ismath:
            self._draw_mathtext(gc, x, y, s, prop, angle)

        elif angle==90:
            self._draw_rotated_text(gc, x, y, s, prop, angle)

        else:
            layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
            l, b, w, h = inkRect
            self.gdkDrawable.draw_layout(gc.gdkGC, x, y-h-b, layout)
Esempio n. 16
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()
        # mathtext using the gtk/gdk method

        try:
            import cairo.numpy
        except:
            verbose.report_error(
                "cairo.numpy module required for _draw_mathtext()")
            return

        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = zeros((N, len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:, i] = fromstring(s, UInt8)

        # get the max alpha at each pixel
        Xs = numerix.mlab.max(Xall, 1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pa = zeros(shape=(imh, imw, 4), typecode=UInt8)
        rgb = gc.get_rgb()
        pa[:, :, 0] = int(rgb[0] * 255)
        pa[:, :, 1] = int(rgb[1] * 255)
        pa[:, :, 2] = int(rgb[2] * 255)
        pa[:, :, 3] = Xs

        surface = cairo.numpy.surface_create_for_array(pa)
        gc.ctx.translate(x, y)
        gc.ctx.show_surface(surface, imw, imh)
Esempio n. 17
0
def rem(x,y):
    """
    Remainder after division.
    rem(x,y) is equivalent to x - y.*fix(x./y) in case y is not zero.
    By convention, rem(x,0) returns None.
    We keep the convention by Matlab:
    "The input x and y must be real arrays of the same size, or real scalars."
    """
    
    x,y = numerix.asarray(x),numerix.asarray(y)
    if numerix.shape(x) == numerix.shape(y) or numerix.shape(y) == ():
        try:
            return x - y * fix(x/y)
        except OverflowError:
            return None
    verbose.report_error('Dimension error')
    return None
Esempio n. 18
0
def norm(x, y=2):
    """
    Norm of a matrix or a vector according to Matlab.
    The description is taken from Matlab:
    
        For matrices...
          NORM(X) is the largest singular value of X, max(svd(X)).
          NORM(X,2) is the same as NORM(X).
          NORM(X,1) is the 1-norm of X, the largest column sum,
                          = max(sum(abs((X)))).
          NORM(X,inf) is the infinity norm of X, the largest row sum,
                          = max(sum(abs((X')))).
          NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
          NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
     
        For vectors...
          NORM(V,P) = sum(abs(V).^P)^(1/P).
          NORM(V) = norm(V,2).
          NORM(V,inf) = max(abs(V)).
          NORM(V,-inf) = min(abs(V)).
    """

    x = numerix.asarray(x)
    if MLab.rank(x) == 2:
        if y == 2:
            return MLab.max(MLab.svd(x)[1])
        elif y == 1:
            return MLab.max(MLab.sum(numerix.absolute((x))))
        elif y == 'inf':
            return MLab.max(MLab.sum(numerix.absolute((MLab.transpose(x)))))
        elif y == 'fro':
            return MLab.sqrt(
                MLab.sum(
                    MLab.diag(numerix.matrixmultiply(MLab.transpose(x), x))))
        else:
            verbose.report_error('Second argument not permitted for matrices')
            return None

    else:
        if y == 'inf':
            return MLab.max(numerix.absolute(x))
        elif y == '-inf':
            return MLab.min(numerix.absolute(x))
        else:
            return numerix.power(
                MLab.sum(numerix.power(numerix.absolute(x), y)), 1 / float(y))
Esempio n. 19
0
def print_figure_fn(figure,
                    filename,
                    dpi=150,
                    facecolor='w',
                    edgecolor='w',
                    orientation='portrait'):
    """
    Render the figure to hardcopy.  Set the figure patch face and
    edge colors.  This is useful because some of the GUIs have a
    gray figure face color background and you'll probably want to
    override this on hardcopy

    orientation - only currently applies to PostScript printing.
    filename - can also be a file object, png format is assumed
    """
    if DEBUG: print 'backend_cairo.FigureCanvasCairo.%s()' % _fn_name()

    root, ext = os.path.splitext(filename)
    ext = ext[1:]
    if ext == '':
        ext = IMAGE_FORMAT_DEFAULT
        filename = filename + '.' + ext

    # save figure state
    origDPI = figure.dpi.get()
    origfacecolor = figure.get_facecolor()
    origedgecolor = figure.get_edgecolor()

    # settings for printing
    figure.dpi.set(dpi)
    figure.set_facecolor(facecolor)
    figure.set_edgecolor(edgecolor)

    ext = ext.lower()
    if isinstance(filename, file):  # eg when do savefig(sys.stdout)
        # assume PNG format
        _save_png(figure, filename)
    elif ext in ('png', 'ps'):  # native formats
        try:
            fileObject = file(filename, 'wb')
        except IOError, exc:
            verbose.report_error("%s: %s" % (exc.filename, exc.strerror))
        else:
            if ext == 'png': _save_png(figure, fileObject)
            else: _save_ps(figure, fileObject, orientation)
Esempio n. 20
0
    def get_gd_color(self, rgb):
        """
        RGB is a unit RGB tuple, return a gd color
        """

        
        try: return self._cached[rgb]
        except KeyError: pass

        r,g,b = rgb
        arg = (int(r*255),int(g*255),int(b*255))
        color = self.im.colorAllocate(  arg )

        if color==-1:
            verbose.report_error('Unable to allocate color %1.3f, %1.3f, %1.3f; using nearest neighbor' % rgb)
            color = self.im.colorClosest(arg)

        self._cached[rgb] = color
        return color
Esempio n. 21
0
    def _get_info(self, font, sym, fontsize, dpi):
        'load the cmfont, metrics and glyph with caching'
        key = font, sym, fontsize, dpi
        tup = self.glyphd.get(key)

        if tup is not None:
            return tup

        basename = self.fontmap[font]

        if latex_to_bakoma.has_key(sym):
            basename, num = latex_to_bakoma[sym]
            sym = self.fonts[basename].get_glyph_name(num)
            num = self.fonts[basename].get_charmap()[num]
        elif len(sym) == 1:
            num = ord(sym)
        else:
            num = 0
            sym = '.notdef'
            verbose.report_error('unrecognized symbol "%s, %d"' % (sym, num))

        if basename not in bakoma_fonts:
            bakoma_fonts.append(basename)
        cmfont = self.fonts[basename]
        cmfont.set_size(fontsize, dpi)
        head = cmfont.get_sfnt_table('head')
        glyph = cmfont.load_char(num)

        xmin, ymin, xmax, ymax = [val / 64.0 for val in glyph.bbox]
        if basename == 'cmex10':
            offset = -(head['yMin'] + 512) / head['unitsPerEm'] * 10.
        else:
            offset = 0.
        metrics = Bunch(advance=glyph.horiAdvance / 64.0,
                        height=glyph.height / 64.0,
                        width=glyph.width / 64.0,
                        xmin=xmin,
                        xmax=xmax,
                        ymin=ymin + offset,
                        ymax=ymax + offset)

        self.glyphd[key] = basename, metrics, sym, offset
        return basename, metrics, '/' + sym, offset
Esempio n. 22
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = zeros((N, len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:, i] = fromstring(s, UInt8)

        # get the max alpha at each pixel
        Xs = numerix.max(Xall, 1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pb = gtk.gdk.Pixbuf(
            gtk.gdk.COLORSPACE_RGB,
            #has_alpha=1, bits_per_sample=8, width=imw, height=imh)
            has_alpha=True,
            bits_per_sample=8,
            width=imw,
            height=imh)

        try:
            pa = pb.get_pixels_array()
        except AttributeError:
            pa = pb.pixel_array
        except RuntimeError, exc:  #  'pygtk was not compiled with Numeric Python support'
            verbose.report_error('mathtext not supported: %s' % exc)
            return
Esempio n. 23
0
    def _get_info(self, font, sym, fontsize, dpi):
        'load the cmfont, metrics and glyph with caching'
        key = font, sym, fontsize, dpi
        tup = self.glyphd.get(key)

        if tup is not None: return tup

        basename = self.fontmap[font]

        if latex_to_bakoma.has_key(sym):
            basename, num = latex_to_bakoma[sym]
            num = self.charmaps[basename][num]
        elif len(sym) == 1:
            num = ord(sym)
        else:
            num = 0
            verbose.report_error('unrecognized symbol "%s"' % sym)

        #print sym, basename, num
        cmfont = self.fonts[basename]
        cmfont.set_size(fontsize, dpi)
        head = cmfont.get_sfnt_table('head')
        glyph = cmfont.load_char(num)

        xmin, ymin, xmax, ymax = [val / 64.0 for val in glyph.bbox]
        if basename == 'cmex10':
            offset = glyph.height / 64.0 / 2 + 256.0 / 64.0 * dpi / 72.0
            #offset = -(head['yMin']+512)/head['unitsPerEm']*10.
        else:
            offset = 0.
        metrics = Bunch(
            advance=glyph.horiAdvance / 64.0,
            height=glyph.height / 64.0,
            width=glyph.width / 64.0,
            xmin=xmin,
            xmax=xmax,
            ymin=ymin + offset,
            ymax=ymax + offset,
        )

        self.glyphd[key] = cmfont, metrics, glyph, offset
        return self.glyphd[key]
Esempio n. 24
0
    def __init__(self, parent, handles, labels, loc, isaxes=True):
        Artist.__init__(self)
        if is_string_like(loc) and not self.codes.has_key(loc):
            verbose.report_error(
                'Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t'
                % (loc, '\n\t'.join(self.codes.keys())))
        if is_string_like(loc): loc = self.codes.get(loc, 1)

        if isaxes:  # parent is an Axes
            self.set_figure(parent.figure)
        else:  # parent is a Figure
            self.set_figure(parent)

        self.parent = parent
        self.set_transform(get_bbox_transform(unit_bbox(), parent.bbox))
        self._loc = loc

        # make a trial box in the middle of the axes.  relocate it
        # based on it's bbox
        left, upper = 0.5, 0.5
        if self.NUMPOINTS == 1:
            self._xdata = array([left + self.HANDLELEN * 0.5])
        else:
            self._xdata = linspace(left, left + self.HANDLELEN, self.NUMPOINTS)
        textleft = left + self.HANDLELEN + self.HANDLETEXTSEP
        self.texts = self._get_texts(labels, textleft, upper)
        self.handles = self._get_handles(handles, self.texts)

        left, top = self.texts[-1].get_position()
        HEIGHT = self._approx_text_height()
        bottom = top - HEIGHT
        left -= self.HANDLELEN + self.HANDLETEXTSEP + self.PAD
        self.legendPatch = Rectangle(
            xy=(left, bottom),
            width=0.5,
            height=HEIGHT * len(self.texts),
            facecolor='w',
            edgecolor='k',
        )
        self._set_artist_props(self.legendPatch)
        self._drawFrame = True
Esempio n. 25
0
    def __init__(self, ax, loc=None, bbox=None):

        Artist.__init__(self)

        if is_string_like(loc) and not self.codes.has_key(loc):
            verbose.report_error('Unrecognized location %s. Falling back on bottom; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys())))
            loc = 'bottom'
        if is_string_like(loc): loc = self.codes.get(loc, 1)
        self.set_figure(ax.figure)
        self._axes = ax
        self._loc = loc
        self._bbox = bbox

        # use axes coords
        self.set_transform(ax.transAxes)

        self._texts = []
        self._cells = {}
        self._autoRows = []
        self._autoColumns = []
        self._autoFontsize = True
Esempio n. 26
0
    def draw_image(self, x, y, im, origin, bbox):
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()
        # works for numpy image, not a numarray image

        try:
            import cairo.numpy
        except:
            verbose.report_error(
                "cairo.numpy module required for draw_image()")
            return

        # bbox - not currently used
        flipud = origin == 'lower'  # not currently used

        ctx = cairo.Context()
        ctx.set_target_surface(self.surface)
        ctx.set_matrix(self.matrix)

        rows, cols, buf = im.buffer_argb32()  # ARGB32, but colors still wrong
        X = fromstring(buf, UInt8)
        X.shape = rows, cols, 4
        #print dir(im)
        #print 'im.get_size()', im.get_size()
        #print 'r,c', rows, cols

        # GTK method
        #rows, cols, s = im.as_str(flipud) # RGBA
        #print 'r,c', rows, cols
        #X = fromstring(s, UInt8)
        #X.shape = rows, cols, 4

        # ARGB32
        surface = cairo.numpy.surface_create_for_array(X)

        # Alternative
        #surface = cairo.surface_create_for_image(buf, cairo.FORMAT_ARGB32, cols, rows) #, stride)
        # error: TypeError: Cannot use string as modifiable buffer

        ctx.translate(x, y)
        ctx.show_surface(surface, cols, rows)
Esempio n. 27
0
    def draw_image(self, x, y, im, origin, bbox):
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()

        try:
            import cairo.numpy
        except:
            verbose.report_error(
                "cairo.numpy module required for draw_image()")
            return

        # bbox - not currently used
        flipud = origin == 'lower'  # not currently used

        ctx = cairo.Context()
        ctx.set_target_surface(self.surface)
        ctx.set_matrix(self.matrix)

        rows, cols, buf = im.buffer_argb32()  # ARGB32, but colors still wrong
        X = fromstring(buf, UInt8)
        X.shape = rows, cols, 4
        #print dir(im)
        #print 'im.get_size()', im.get_size()
        #print 'r,c', rows, cols

        # GTK method
        #rows, cols, s = im.as_str(flipud) # RGBA
        #print 'r,c', rows, cols
        #X = fromstring(s, UInt8)
        #X.shape = rows, cols, 4

        # ARGB32
        try:
            # works for numpy image, not a numarray image
            surface = cairo.numpy.surface_create_for_array(X)
        except TypeError, exc:
            verbose.report_error("%s: %s" % (_fn_name(), exc))
            return
Esempio n. 28
0
def Grayscale(N=LUTSIZE):
    verbose.report_error("Grayscale deprecated, please use cm.gray instead")
    return colors.LinearSegmentedColormap('gray', _gray_data, N)
Esempio n. 29
0
def ColormapJet(N=LUTSIZE):
    verbose.report_error("ColormapJet deprecated, please use cm.jet instead")
    return colors.LinearSegmentedColormap('jet', _jet_data, N)
Esempio n. 30
0
            verbose.report_error("%s: %s" % (exc.filename, exc.strerror))
        else:
            if ext == 'png': _save_png(figure, fileObject)
            else: _save_ps(figure, fileObject, orientation)

    elif ext in ('eps', 'svg'):  # backend_svg/ps
        if ext == 'eps':
            from backend_ps import FigureCanvasPS as FigureCanvas
        else:
            from backend_svg import FigureCanvasSVG as FigureCanvas
        fc = FigureCanvas(figure)
        fc.print_figure(filename, dpi, facecolor, edgecolor, orientation)

    else:
        verbose.report_error(
            'Format "%s" is not supported.\nSupported formats: %s.' %
            (ext, ', '.join(IMAGE_FORMAT)))

    # restore the new params
    figure.dpi.set(origDPI)
    figure.set_facecolor(origfacecolor)
    figure.set_edgecolor(origedgecolor)


def _save_png(figure, fileObject):
    width, height = figure.get_width_height()
    width, height = int(width), int(height)

    ctx = cairo.Context()
    # 4 png formats supported
    ctx.set_target_png(fileObject, cairo.FORMAT_ARGB32, width, height)