Example #1
0
def filled_regions(epsoutfile):
    x = arange(0.0, 10.0, 0.1)
    phi = arange(0.0, 2.0*pi, 0.1)
    x_circ = cos(phi)-1.5
    y_circ = sin(phi)-1.0

    x_ell = 1.5*cos(phi)+1.0
    y_ell = 0.5*sin(phi)+0.5

    g=pyxgraph(xlabel=r"$x$", ylabel=r"$y$", xlimits=(-3.0, 3.0),
               ylimits=(-4.0, 4.0), key=False)      
    g.pyxplot((x, -sin(x)-1.0), style="p", title=None)  # we need at least one plot!!
                                                   # even if invisible
    p1 = convert_to_path(g, x_circ, y_circ)
    g.stroke(p1, [pyx.deco.filled([pyx.color.rgb(0.8, 0.8, 0.8)])])

    p2 = convert_to_path(g, x_ell, y_ell)
    g.stroke(p2, [pyx.deco.stroked([pyx.color.rgb(0.8, 0.2, 0.0)]),
                 pyx.style.linewidth(0.35),
                 pyx.deco.filled([pyx.color.rgb(0.8, 0.8, 0.8)]),
                 ])

    # a more funny shape
    p3 = convert_to_path(g, phi/2.0/pi*x_ell-2.4, 3*y_ell+0.5)
    g.fill(p3, [pyx.deco.filled([pyx.color.rgb(0.2, 0.8, 0.2)]),
                 ])

    g.pyxsave(epsoutfile)
Example #2
0
    def get_rotation_matrix(self, x0, y0):

        theta = pi / 180.0 * self.get_rotation()
        # translate x0,y0 to origin
        Torigin = array([[1, 0, -x0], [0, 1, -y0], [0, 0, 1]])

        # rotate by theta
        R = array([[cos(theta), -sin(theta), 0], [sin(theta),
                                                  cos(theta), 0], [0, 0, 1]])

        # translate origin back to x0,y0
        Tback = array([[1, 0, x0], [0, 1, y0], [0, 0, 1]])

        return dot(dot(Tback, R), Torigin)
Example #3
0
    def get_rotation_matrix(self, x0, y0):

        theta = -pi / 180.0 * self.get_rotation()
        # translate x0,y0 to origin
        Torigin = Matrix([[1, 0, -x0], [0, 1, -y0], [0, 0, 1]])

        # rotate by theta
        R = Matrix([[cos(theta), sin(theta), 0], [-sin(theta),
                                                  cos(theta), 0], [0, 0, 1]])

        # translate origin back to x0,y0
        Tback = Matrix([[1, 0, x0], [0, 1, y0], [0, 0, 1]])

        return Tback * R * Torigin
Example #4
0
    def __init__(self,
                 dpi,
                 numsides,
                 rotation = 0 ,
                 sizes = (1,),
                 **kwargs):
        """
        Draw a regular polygon with numsides.  sizes gives the area of
        the circle circumscribing the regular polygon and rotation is
        the rotation of the polygon in radians.

        offsets are a sequence of x,y tuples that give the centers of
        the polygon in data coordinates, and transOffset is the
        Transformation instance used to transform the centers onto the
        canvas.

        dpi is the figure dpi instance, and is required to do the area
        scaling.
        """
        PatchCollection.__init__(self,**kwargs)
        self._sizes = asarray(sizes)
        self._dpi = dpi

        r = 1.0/math.sqrt(math.pi)  # unit area

        theta = (2*math.pi/numsides)*arange(numsides) + rotation
        self._verts = zip( r*sin(theta), r*cos(theta) )
Example #5
0
    def __init__(self,
                 dpi,
                 numsides,
                 rotation = 0 ,
                 sizes = (1,),
                 **kwargs):
        """
        Draw a regular polygon with numsides.  sizes gives the area of
        the circle circumscribing the regular polygon and rotation is
        the rotation of the polygon in radians.

        offsets are a sequence of x,y tuples that give the centers of
        the polygon in data coordinates, and transOffset is the
        Transformation instance used to transform the centers onto the
        canvas.

        dpi is the figure dpi instance, and is required to do the area
        scaling.
        """
        PatchCollection.__init__(self,**kwargs)
        self._sizes = asarray(sizes)
        self._dpi = dpi

        r = 1.0/math.sqrt(math.pi)  # unit area

        theta = (2*math.pi/numsides)*arange(numsides) + rotation
        self._verts = zip( r*sin(theta), r*cos(theta) )
Example #6
0
    def _draw_circle(self, renderer, gc, xt, yt, point=False):

        w = renderer.points_to_pixels(self._markersize)
        if point:
            w *= self._point_size_reduction


        rgbFace = self._get_rgb_face()

        if self._newstyle:
            N = 50.0
            r = w/2.
            rads = (2*math.pi/N)*arange(N)
            xs = r*cos(rads)
            ys = r*sin(rads)
            # todo: use curve3!
            path = agg.path_storage()
            path.move_to(xs[0], ys[0])
            for x, y in zip(xs[1:], ys[1:]):
                path.line_to(x, y)

            path.end_poly()
            renderer.draw_markers(gc, path, rgbFace, xt, yt, self._transform)
        else:
            for (x,y) in zip(xt, yt):
                renderer.draw_arc(gc, rgbFace,
                                  x, y, w, w, 0.0, 360.0)
Example #7
0
    def get_proj(self):
        """Create the projection matrix from the current viewing
        position.

        elev stores the elevation angle in the z plane
        azim stores the azimuth angle in the x,y plane

        dist is the distance of the eye viewing point from the object
        point.

        """
        relev,razim = nx.pi * self.elev/180, nx.pi * self.azim/180

        xmin,xmax = self.get_w_xlim()
        ymin,ymax = self.get_w_ylim()
        zmin,zmax = self.get_w_zlim()

        # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
        worldM = proj3d.world_transformation(xmin,xmax,
                                             ymin,ymax,
                                             zmin,zmax)

        # look into the middle of the new coordinates
        R = nx.array([0.5,0.5,0.5])
        #
        xp = R[0] + nx.cos(razim)*nx.cos(relev)*self.dist
        yp = R[1] + nx.sin(razim)*nx.cos(relev)*self.dist
        zp = R[2] + nx.sin(relev)*self.dist

        E = nx.array((xp, yp, zp))
        #
        self.eye = E
        self.vvec = R - E
        self.vvec = self.vvec / proj3d.mod(self.vvec)

        if abs(relev) > nx.pi/2:
            # upside down
            V = nx.array((0,0,-1))
        else:
            V = nx.array((0,0,1))
        zfront,zback = -self.dist,self.dist

        viewM = proj3d.view_transformation(E,R,V)
        perspM = proj3d.persp_transformation(zfront,zback)
        M0 = nx.matrixmultiply(viewM,worldM)
        M = nx.matrixmultiply(perspM,M0)
        return M
Example #8
0
def colorbars(epsoutfile):
    x = (arange(50.0)-25)/2.0
    y = (arange(50.0)-25)/2.0
    r = sqrt(x[:,NewAxis]**2+y**2)
    z = 5.0*cos(r)  

    colmap = ColMapper.ColorMapper("yellow-red", exponent=0.55, brightness=0.5)
    lut = colmap.generate_lut()

    c = pyx.canvas.canvas()
    g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)),
                 width=6, height=6)
    g.pyxplot("y(x)=sin(x)", style="p")  # FIXME: can't do empty plots!
    g.pyxplotarray(z, colmap=lut)
    c.insert(g)

    minz = minvalue=min(ravel(z))
    maxz = maxvalue=max(ravel(z))

    # --- vertical bars
    dist = 1.2
    for orientation, position in [("vertical", "right"),
                                  ("vertical", "middle"),
                                  ("vertical2", "middle")]:
        cb = pyxcolorbar(lut=lut, frame=g,
                         pos=(dist, 0),
                         orientation = orientation,
                         position = position,
                         minvalue = minz, maxvalue=maxz)
        # add a short note on the style:
        txt = orientation[0]
        if "2" in orientation:
            txt += "2"
        txt += ", "+position[0]            
        cb.pyxlabel( (0.0, 1.3), txt, style=[pyx.text.halign.left])

        c.insert(cb)
        dist = dist + 0.5

    # horizontal ones:
    dist = -0.3
    for orientation, position in [("horizontal", "middle"),
                                  ("horizontal2", "middle")]:
        cb = pyxcolorbar(lut=lut, frame=g, pos=(0.0, dist),
                         orientation = orientation,
                         position = position,
                         minvalue = minz, maxvalue=maxz)
        # add a short note on the style:
        txt = orientation[0]
        if "2" in orientation:
            txt += "2"
        txt += ", "+position[0]            
        cb.pyxlabel( (1.3, 0.5), txt, style=[pyx.text.halign.left])

        c.insert(cb)
        dist = dist - 0.3
    
    pyxsave(c, epsoutfile)
Example #9
0
    def get_rotation_matrix(self, x0, y0):

        theta = -pi/180.0*self.get_angle()
        # translate x0,y0 to origin
        Torigin = Matrix([ [1, 0, -x0],
                           [0, 1, -y0],
                           [0, 0, 1  ]]) 
        
        # rotate by theta
        R = Matrix([ [cos(theta),  sin(theta), 0],
                     [-sin(theta), cos(theta), 0],
                     [0,           0,          1]]) 

        # translate origin back to x0,y0
        Tback = Matrix([ [1, 0, x0],
                         [0, 1, y0],
                         [0, 0, 1  ]]) 


        return Tback*R*Torigin
Example #10
0
    def get_rotation_matrix(self, x0, y0):

        theta = pi/180.0*self.get_rotation()
        # translate x0,y0 to origin
        Torigin = array([ [1, 0, -x0],
                           [0, 1, -y0],
                           [0, 0, 1  ]]) 
        
        # rotate by theta
        R = array([ [cos(theta),  -sin(theta), 0],
                     [sin(theta), cos(theta), 0],
                     [0,           0,          1]]) 

        # translate origin back to x0,y0
        Tback = array([ [1, 0, x0],
                         [0, 1, y0],
                         [0, 0, 1  ]]) 


        return dot(dot(Tback,R), Torigin)
Example #11
0
def array_example1(epsoutfile):
    x = (arange(100.0)-50)/25.0
    y = (arange(100.0)-50)/25.0
    # Important: z[y, x] -- y first!
    z = 5.0*sin(2*x[NewAxis, :]) + 3.0*cos(3*y[:, NewAxis])

    g=pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)),
               width=6, height=6, key=False)
    g.pyxplotcontour(z, x, y, levels=15, colors='map',
                     colmap=ColMapper.ColorMapper("pm3d",
                                                exponent=1.0, brightness=0.2))
    g.pyxsave(epsoutfile)
Example #12
0
    def __init__(self, xy, numVertices, radius=5, orientation=0, **kwargs):

        Patch.__init__(self, **kwargs)

        self._xy = xy
        self.numVertices = numVertices
        self.radius = radius
        self.orientation = orientation

        theta = 2 * pi / self.numVertices * arange(self.numVertices) + self.orientation
        r = self.radius
        xs = self.xy[0] + r * cos(theta)
        ys = self.xy[1] + r * sin(theta)

        self.verts = zip(xs, ys)
Example #13
0
    def __init__(self, xy, numVertices, radius=5, orientation=0, **kwargs):

        Patch.__init__(self, **kwargs)

        self.xy = xy
        self.numVertices = numVertices
        self.radius = radius
        self.orientation = orientation

        theta = 2*pi/self.numVertices*arange(self.numVertices) + \
                self.orientation
        r = self.radius
        xs = self.xy[0] + r * cos(theta)
        ys = self.xy[1] + r * sin(theta)

        self.verts = zip(xs, ys)
Example #14
0
def simple1(epsoutfile):
    x = arange(0.0, 10.0, 0.1)

    g=pyxgraph(title="A first plot ;-)",  # one graph (essentially a
               xlabel=r"$x$",             #    pyx.grapxy instance)
               ylabel=r"$f(x)$",
               key="bl")     
    g.pyxplot("y(x)=sin(x)", style="p", title=None)
    
    g.pyxplot((x, cos(x)))
    g.pyxplot("test_data.dat", style="l", lt=0,
                              lw=3, title="Optional title")
    g.pyxplot(("test_data.dat",1,4), title=False)
    g.pyxplot(("test_data.dat",1, "$4+$5*$1/4"), style="lp", pt=6,
              lw=0.1, ps=0.8, title="blurb2",
              color='cyan', linecolor='purple')
    g.pyxsave(epsoutfile)
Example #15
0
def array_example2(epsoutfile):
    x = (arange(100.0)-50)/25.0
    y = (arange(100.0)-50)/25.0
    # Important: z[y, x] -- y first!
    z = 5.0*sin(2*x[NewAxis, :]) + 3.0*cos(3*y[:, NewAxis])

    colmap = ColMapper.ColorMapper("yellow-red", invert=1, exponent=0.55,
                                   brightness=0.5)
    #lut = colmap.generate_lut()

#    c = pyx.canvas.canvas()
    g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)),
                 width=6, height=6, key=False)
    g.pyxplotarray(z[::-1,:], colmap=colmap)
    g.pyxplotcontour(z, x, y, colors='color', color='black', labels=True)
   
    pyxsave(g, epsoutfile)
Example #16
0
    def __init__(self, center, r, theta1, theta2, dtheta=0.1, **kwargs):
        """
        Draw a wedge centered at x,y tuple center with radius r that
        sweeps theta1 to theta2 (angles)


        kwargs are Polygon keyword args

        dtheta is the resolution in degrees

        """
        xc, yc = center
        rads = (math.pi / 180.0) * arange(theta1, theta2 + 0.1 * dtheta, dtheta)
        xs = r * cos(rads) + xc
        ys = r * sin(rads) + yc
        verts = [center]
        verts.extend([(x, y) for x, y in zip(xs, ys)])

        Polygon.__init__(self, verts, **kwargs)
Example #17
0
    def __init__(self, center, r, theta1, theta2, dtheta=0.1, **kwargs):
        """
        Draw a wedge centered at x,y tuple center with radius r that
        sweeps theta1 to theta2 (angles)


        kwargs are Polygon keyword args

        dtheta is the resolution in degrees

        """
        xc, yc = center
        rads = (math.pi / 180.) * arange(theta1, theta2 + 0.1 * dtheta, dtheta)
        xs = r * cos(rads) + xc
        ys = r * sin(rads) + yc
        verts = [center]
        verts.extend([(x, y) for x, y in zip(xs, ys)])

        Polygon.__init__(self, verts, **kwargs)
Example #18
0
def array_example3(epsoutfile):
    x = (arange(200.0) - 100) / 10.0
    y = (arange(200.0) - 100) / 10.0
    r = sqrt(x[:, NewAxis] ** 2 + y ** 2)
    z = 5.0 * cos(r)

    colmap1 = ColMapper.ColorMapper("red")
    colmap1.exponent = 0.9
    colmap1.invert = True

    colmap2 = ColMapper.ColorMapper("green")
    colmap2.exponent = 0.9

    colmap3 = ColMapper.ColorMapper("green")
    colmap3.invert = True
    colmap3.exponent = 0.9

    colmap4 = ColMapper.ColorMapper("blue")
    colmap4.exponent = 0.9

    colmap = ColMapper.SegmentedColorMapping(
        [(-5.0, -2.5, colmap1), (-2.5, 0.0, colmap2), (0.0, 2.5, colmap3), (2.5, 5.0, colmap4)], -5.0, 5.0
    )

    #     colmap = ColMapper.example_SegmentedColorMapping(min(ravel(z)),max(ravel(z)))
    lut = colmap.generate_lut()

    pilbitmap = ColMapper.Array2PIL(z, lut=lut)

    c = pyx.canvas.canvas()
    g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6, key=False)
    g.pyxplot("y(x)=sin(x)+20", style="p")  # FIXME: can't do empty plots!

    g.pyxbitmap(pilbitmap)

    c.insert(g)

    cb = pyxcolorbar(lut=lut, frame=g, pos=(1.1, 0.0), minvalue=min(ravel(z)), maxvalue=max(ravel(z)))
    c.insert(cb)

    pyxsave(c, epsoutfile)
Example #19
0
    def _draw_circle(self, renderer, gc, xt, yt):

        w = h = renderer.points_to_pixels(self._markersize)
        
        rgbFace = self._get_rgb_face()

        if self._newstyle:
            N = 50.0
            r = w/2.
            rads = (2*math.pi/N)*arange(N)
            xs = r*cos(rads)
            ys = r*sin(rads)
            verts = [(MOVETO, xs[0], ys[0])]
            verts.extend([(LINETO, x, y) for x, y in zip(xs[1:], ys[1:])])
            CLOSE = self._get_close(rgbFace)
            verts.append(CLOSE)
            renderer.draw_markers(gc, verts, xt, yt, self._transform)
        else:
            for (x,y) in zip(xt, yt):
                renderer.draw_arc(gc, rgbFace,
                                  x, y, w, h, 0.0, 360.0)
Example #20
0
def array_example2(epsoutfile):
    x = (arange(50.0)-25)/2.0
    y = (arange(50.0)-25)/2.0
    r = sqrt(x[:,NewAxis]**2+y**2)
    z = 5.0*cos(r)  

    colmap = ColMapper.ColorMapper("yellow-red", exponent=0.55, brightness=0.5)
    lut = colmap.generate_lut()

    c = pyx.canvas.canvas()
    g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)),
                 width=6, height=6)
    g.pyxplot("y(x)=sin(x)", style="p")  # FIXME: can't do empty plots!
    g.pyxplotarray(z, colmap=lut)
    c.insert(g)

    cb = pyxcolorbar(lut=lut, frame=g, pos=(1.1,0.0),
                     minvalue=min(ravel(z)), maxvalue=max(ravel(z)))
    c.insert(cb)
    
    pyxsave(c, epsoutfile)
Example #21
0
    def update_coords(self, renderer):
        """Computes the actual x,y coordinates for
        text based on the input x,y and the
        dashlength. Since the rotation is with respect
        to the actual canvas's coordinates we need to
        map back and forth.
        """
        dashx, dashy = self.get_position()
        dashlength = self.get_dashlength()
        # Shortcircuit this process if we don't have a dash
        if dashlength == 0.0:
            self._x, self._y = dashx, dashy
            return

        dashrotation = self.get_dashrotation()
        dashdirection = self.get_dashdirection()
        dashpad = self.get_dashpad()
        dashpush = self.get_dashpush()

        angle = get_rotation(dashrotation)
        theta = pi * (angle / 180.0 + dashdirection - 1)
        cos_theta, sin_theta = cos(theta), sin(theta)

        transform = self.get_transform()

        # Compute the dash end points
        # The 'c' prefix is for canvas coordinates
        cxy = array(transform.xy_tup((dashx, dashy)))
        cd = array([cos_theta, sin_theta])
        c1 = cxy + dashpush * cd
        c2 = cxy + (dashpush + dashlength) * cd

        (x1, y1) = transform.inverse_xy_tup(tuple(c1))
        (x2, y2) = transform.inverse_xy_tup(tuple(c2))
        self.dashline.set_data((x1, x2), (y1, y2))

        # We now need to extend this vector out to
        # the center of the text area.
        # The basic problem here is that we're "rotating"
        # two separate objects but want it to appear as
        # if they're rotated together.
        # This is made non-trivial because of the
        # interaction between text rotation and alignment -
        # text alignment is based on the bbox after rotation.
        # We reset/force both alignments to 'center'
        # so we can do something relatively reasonable.
        # There's probably a better way to do this by
        # embedding all this in the object's transformations,
        # but I don't grok the transformation stuff
        # well enough yet.
        we = Text.get_window_extent(self, renderer=renderer)
        w, h = we.width(), we.height()
        # Watch for zeros
        if sin_theta == 0.0:
            dx = w
            dy = 0.0
        elif cos_theta == 0.0:
            dx = 0.0
            dy = h
        else:
            tan_theta = sin_theta / cos_theta
            dx = w
            dy = w * tan_theta
            if dy > h or dy < -h:
                dy = h
                dx = h / tan_theta
        cwd = array([dx, dy]) / 2
        cwd *= 1 + dashpad / sqrt(dot(cwd, cwd))
        cw = c2 + (dashdirection * 2 - 1) * cwd

        self._x, self._y = transform.inverse_xy_tup(tuple(cw))

        # Now set the window extent
        # I'm not at all sure this is the right way to do this.
        we = Text.get_window_extent(self, renderer=renderer)
        self._twd_window_extent = we.deepcopy()
        self._twd_window_extent.update(((c1[0], c1[1]), ), False)

        # Finally, make text align center
        Text.set_horizontalalignment(self, 'center')
        Text.set_verticalalignment(self, 'center')
Example #22
0
    def break_linecontour(self, linecontour, rot, labelwidth, ind):
        "break a contour in two contours at the location of the label"
        lcsize = len(linecontour)
        hlw = int(labelwidth/2)

        #length of label in screen coords
        ylabel = abs(hlw * sin(rot*pi/180))
        xlabel = abs(hlw * cos(rot*pi/180))

        trans = self.ax.transData

        slc = trans.seq_xy_tups(linecontour)
        x,y = slc[ind]
        xx= array(slc)[:,0].copy()
        yy=array(slc)[:,1].copy()

        #indices which are under the label
        inds=nonzero(((xx < x+xlabel) & (xx > x-xlabel)) &
                     ((yy < y+ylabel) & (yy > y-ylabel)))

        if len(inds) >0:
            #if the label happens to be over the beginning of the
            #contour, the entire contour is removed, i.e.
            #indices to be removed are
            #inds= [0,1,2,3,305,306,307]
            #should rewrite this in a better way
            linds = nonzero(inds[1:]- inds[:-1] != 1)
            if inds[0] == 0 and len(linds) != 0:
                ii = inds[linds[0]]
                lc1 =linecontour[ii+1:inds[ii+1]]
                lc2 = []

            else:
                lc1=linecontour[:inds[0]]
                lc2= linecontour[inds[-1]+1:]

        else:
            lc1=linecontour[:ind]
            lc2 = linecontour[ind+1:]


        if rot <0:
            new_x1, new_y1 = x-xlabel, y+ylabel
            new_x2, new_y2 = x+xlabel, y-ylabel
        else:
            new_x1, new_y1 = x-xlabel, y-ylabel
            new_x2, new_y2 = x+xlabel, y+ylabel

        new_x1d, new_y1d = trans.inverse_xy_tup((new_x1, new_y1))
        new_x2d, new_y2d = trans.inverse_xy_tup((new_x2, new_y2))

        if rot > 0:
            if len(lc1) > 0 and (lc1[-1][0] <= new_x1d) and (lc1[-1][1] <= new_y1d):
                lc1.append((new_x1d, new_y1d))

            if len(lc2) > 0 and (lc2[0][0] >= new_x2d) and (lc2[0][1] >= new_y2d):
                lc2.insert(0, (new_x2d, new_y2d))
        else:
            if len(lc1) > 0 and ((lc1[-1][0] <= new_x1d) and (lc1[-1][1] >= new_y1d)):
                lc1.append((new_x1d, new_y1d))

            if len(lc2) > 0 and ((lc2[0][0] >= new_x2d) and (lc2[0][1] <= new_y2d)):
                lc2.insert(0, (new_x2d, new_y2d))

        return [lc1,lc2]
Example #23
0
def text_update_coords(self, renderer):
    """Modified method update_coords from TextWithDash

    I could not understand the original text offset calculations and
    it gave bad results for the angles I was using.  This looks
    better, although the text bounding boxes look a little
    inconsistent
    """
    
    (x, y) = self.get_position()
    dashlength = self.get_dashlength()

    # Shortcircuit this process if we don't have a dash
    if dashlength == 0.0:
        self._mytext.set_position((x, y))
        return

    dashrotation = self.get_dashrotation()
    dashdirection = self.get_dashdirection()
    dashpad = self.get_dashpad()
    dashpush = self.get_dashpush()
    transform = self.get_transform()

    angle = text.get_rotation(dashrotation)

    theta = pi*(angle/180.0+dashdirection-1)
    cos_theta, sin_theta = cos(theta), sin(theta)

    # Compute the dash end points
    # The 'c' prefix is for canvas coordinates
    cxy = array(transform.xy_tup((x, y)))
    cd = array([cos_theta, sin_theta])
    c1 = cxy+dashpush*cd
    c2 = cxy+(dashpush+dashlength)*cd
    (x1, y1) = transform.inverse_xy_tup(tuple(c1))
    (x2, y2) = transform.inverse_xy_tup(tuple(c2))
    self.dashline.set_data((x1, x2), (y1, y2))

    # We now need to extend this vector out to
    # the center of the text area.
    # The basic problem here is that we're "rotating"
    # two separate objects but want it to appear as
    # if they're rotated together.
    # This is made non-trivial because of the
    # interaction between text rotation and alignment -
    # text alignment is based on the bbox after rotation.
    # We reset/force both alignments to 'center'
    # so we can do something relatively reasonable.
    # There's probably a better way to do this by
    # embedding all this in the object's transformations,
    # but I don't grok the transformation stuff
    # well enough yet.
    we = self._mytext.get_window_extent(renderer=renderer)
    w, h = we.width(), we.height()
    off = array([cos_theta*(w/2+2)-1,sin_theta*(h+1)-1])
    off = array([cos_theta*(w/2),sin_theta*(h/2)])
    dir = array([cos_theta,sin_theta])*dashpad
    cw = c2 + off +dir
    
    self._mytext.set_position(transform.inverse_xy_tup(tuple(cw)))
    # Now set the window extent
    # I'm not at all sure this is the right way to do this.
    we = self._mytext.get_window_extent(renderer=renderer)
    self._window_extent = we.deepcopy()
    self._window_extent.update(((c1[0], c1[1]),), False)
    
    # Finally, make text align center
    self._mytext.set_horizontalalignment('center')
    self._mytext.set_verticalalignment('center')
Example #24
0
    def update_coords(self, renderer):
        """Computes the actual x,y coordinates for
        self._mytext based on the input x,y and the
        dashlength. Since the rotation is with respect
        to the actual canvas's coordinates we need to
        map back and forth.
        """
        (x, y) = self.get_position()
        dashlength = self.get_dashlength()

        # Shortcircuit this process if we don't have a dash
        if dashlength == 0.0:
            self._mytext.set_position((x, y))
            return

        dashrotation = self.get_dashrotation()
        dashdirection = self.get_dashdirection()
        dashpad = self.get_dashpad()
        dashpush = self.get_dashpush()
        transform = self.get_transform()

        angle = get_rotation(dashrotation)
        theta = pi*(angle/180.0+dashdirection-1)
        cos_theta, sin_theta = cos(theta), sin(theta)

        # Compute the dash end points
        # The 'c' prefix is for canvas coordinates
        cxy = array(transform.xy_tup((x, y)))
        cd = array([cos_theta, sin_theta])
        c1 = cxy+dashpush*cd
        c2 = cxy+(dashpush+dashlength)*cd
        (x1, y1) = transform.inverse_xy_tup(tuple(c1))
        (x2, y2) = transform.inverse_xy_tup(tuple(c2))
        self.dashline.set_data((x1, x2), (y1, y2))

        # We now need to extend this vector out to
        # the center of the text area.
        # The basic problem here is that we're "rotating"
        # two separate objects but want it to appear as
        # if they're rotated together.
        # This is made non-trivial because of the
        # interaction between text rotation and alignment -
        # text alignment is based on the bbox after rotation.
        # We reset/force both alignments to 'center'
        # so we can do something relatively reasonable.
        # There's probably a better way to do this by
        # embedding all this in the object's transformations,
        # but I don't grok the transformation stuff
        # well enough yet.
        we = self._mytext.get_window_extent(renderer=renderer)
        w, h = we.width(), we.height()
        # Watch for zeros
        if sin_theta == 0.0:
            dx = w
            dy = 0.0
        elif cos_theta == 0.0:
            dx = 0.0
            dy = h
        else:
            tan_theta = sin_theta/cos_theta
            dx = w
            dy = w*tan_theta
            if dy > h or dy < -h:
                dy = h
                dx = h/tan_theta
        cwd = array([dx, dy])/2
        cwd *= 1+dashpad/sqrt(dot(cwd,cwd))
        cw = c2+(dashdirection*2-1)*cwd
        self._mytext.set_position(transform.inverse_xy_tup(tuple(cw)))

        # Now set the window extent
        # I'm not at all sure this is the right way to do this.
        we = self._mytext.get_window_extent(renderer=renderer)
        self._window_extent = we.deepcopy()
        self._window_extent.update(((c1[0], c1[1]),), False)

        # Finally, make text align center
        self._mytext.set_horizontalalignment('center')
        self._mytext.set_verticalalignment('center')
Example #25
0
 def _update_verts(self):
     r = 1.0 / math.sqrt(math.pi)  # unit area
     theta = (2 * math.pi / self.numsides) * arange(
         self.numsides) + self.rotation
     self._verts = zip(r * sin(theta), r * cos(theta))
Example #26
0
def text_update_coords(self, renderer):
    """Modified method update_coords from TextWithDash

    I could not understand the original text offset calculations and
    it gave bad results for the angles I was using.  This looks
    better, although the text bounding boxes look a little
    inconsistent
    """

    (x, y) = self.get_position()
    dashlength = self.get_dashlength()

    # Shortcircuit this process if we don't have a dash
    if dashlength == 0.0:
        self._mytext.set_position((x, y))
        return

    dashrotation = self.get_dashrotation()
    dashdirection = self.get_dashdirection()
    dashpad = self.get_dashpad()
    dashpush = self.get_dashpush()
    transform = self.get_transform()

    angle = text.get_rotation(dashrotation)

    theta = pi * (angle / 180.0 + dashdirection - 1)
    cos_theta, sin_theta = cos(theta), sin(theta)

    # Compute the dash end points
    # The 'c' prefix is for canvas coordinates
    cxy = array(transform.xy_tup((x, y)))
    cd = array([cos_theta, sin_theta])
    c1 = cxy + dashpush * cd
    c2 = cxy + (dashpush + dashlength) * cd
    (x1, y1) = transform.inverse_xy_tup(tuple(c1))
    (x2, y2) = transform.inverse_xy_tup(tuple(c2))
    self.dashline.set_data((x1, x2), (y1, y2))

    # We now need to extend this vector out to
    # the center of the text area.
    # The basic problem here is that we're "rotating"
    # two separate objects but want it to appear as
    # if they're rotated together.
    # This is made non-trivial because of the
    # interaction between text rotation and alignment -
    # text alignment is based on the bbox after rotation.
    # We reset/force both alignments to 'center'
    # so we can do something relatively reasonable.
    # There's probably a better way to do this by
    # embedding all this in the object's transformations,
    # but I don't grok the transformation stuff
    # well enough yet.
    we = self._mytext.get_window_extent(renderer=renderer)
    w, h = we.width(), we.height()
    off = array([cos_theta * (w / 2 + 2) - 1, sin_theta * (h + 1) - 1])
    off = array([cos_theta * (w / 2), sin_theta * (h / 2)])
    dir = array([cos_theta, sin_theta]) * dashpad
    cw = c2 + off + dir

    self._mytext.set_position(transform.inverse_xy_tup(tuple(cw)))
    # Now set the window extent
    # I'm not at all sure this is the right way to do this.
    we = self._mytext.get_window_extent(renderer=renderer)
    self._window_extent = we.deepcopy()
    self._window_extent.update(((c1[0], c1[1]), ), False)

    # Finally, make text align center
    self._mytext.set_horizontalalignment('center')
    self._mytext.set_verticalalignment('center')
Example #27
0
    def break_linecontour(self, linecontour, rot, labelwidth, ind):
        "break a contour in two contours at the location of the label"
        lcsize = len(linecontour)
        hlw = int(labelwidth / 2)

        #length of label in screen coords
        ylabel = abs(hlw * sin(rot * pi / 180))
        xlabel = abs(hlw * cos(rot * pi / 180))

        trans = self.ax.transData

        slc = trans.seq_xy_tups(linecontour)
        x, y = slc[ind]
        xx = array(slc)[:, 0].copy()
        yy = array(slc)[:, 1].copy()

        #indices which are under the label
        inds = nonzero(((xx < x + xlabel) & (xx > x - xlabel))
                       & ((yy < y + ylabel) & (yy > y - ylabel)))

        if len(inds) > 0:
            #if the label happens to be over the beginning of the
            #contour, the entire contour is removed, i.e.
            #indices to be removed are
            #inds= [0,1,2,3,305,306,307]
            #should rewrite this in a better way
            linds = nonzero(inds[1:] - inds[:-1] != 1)
            if inds[0] == 0 and len(linds) != 0:
                ii = inds[linds[0]]
                lc1 = linecontour[ii + 1:inds[ii + 1]]
                lc2 = []

            else:
                lc1 = linecontour[:inds[0]]
                lc2 = linecontour[inds[-1] + 1:]

        else:
            lc1 = linecontour[:ind]
            lc2 = linecontour[ind + 1:]

        if rot < 0:
            new_x1, new_y1 = x - xlabel, y + ylabel
            new_x2, new_y2 = x + xlabel, y - ylabel
        else:
            new_x1, new_y1 = x - xlabel, y - ylabel
            new_x2, new_y2 = x + xlabel, y + ylabel

        new_x1d, new_y1d = trans.inverse_xy_tup((new_x1, new_y1))
        new_x2d, new_y2d = trans.inverse_xy_tup((new_x2, new_y2))

        if rot > 0:
            if len(lc1) > 0 and (lc1[-1][0] <= new_x1d) and (lc1[-1][1] <=
                                                             new_y1d):
                lc1.append((new_x1d, new_y1d))

            if len(lc2) > 0 and (lc2[0][0] >= new_x2d) and (lc2[0][1] >=
                                                            new_y2d):
                lc2.insert(0, (new_x2d, new_y2d))
        else:
            if len(lc1) > 0 and ((lc1[-1][0] <= new_x1d) and
                                 (lc1[-1][1] >= new_y1d)):
                lc1.append((new_x1d, new_y1d))

            if len(lc2) > 0 and ((lc2[0][0] >= new_x2d) and
                                 (lc2[0][1] <= new_y2d)):
                lc2.insert(0, (new_x2d, new_y2d))

        return [lc1, lc2]
Example #28
0
def rot_x(V, alpha):
    cosa, sina = nx.cos(alpha), nx.sin(alpha)
    M1 = nx.array([[1, 0, 0, 0], [0, cosa, -sina, 0], [0, sina, cosa, 0],
                   [0, 0, 0, 0]])
    #
    return nx.matrixmultiply(M1, V)