Example #1
0
    def _set_lim_and_transforms(self):
        # A view limit where the minimum radius can be locked if the user
        # specifies an alternate origin.
        self._originViewLim = mtransforms.LockableBbox(self.viewLim)

        # Handle angular offset and direction.
        self._direction = mtransforms.Affine2D() \
            .scale(self._default_theta_direction, 1.0)
        self._theta_offset = mtransforms.Affine2D() \
            .translate(self._default_theta_offset, 0.0)
        self.transShift = self._direction + self._theta_offset
        # A view limit shifted to the correct location after accounting for
        # orientation and offset.
        self._realViewLim = mtransforms.TransformedBbox(
            self.viewLim, self.transShift)

        # Transforms the x and y axis separately by a scale factor
        # It is assumed that this part will have non-linear components
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        # Scale view limit into a bbox around the selected wedge. This may be
        # smaller than the usual unit axes rectangle if not plotting the full
        # circle.
        self.axesLim = _WedgeBbox((0.5, 0.5), self._realViewLim,
                                  self._originViewLim)

        # Scale the wedge to fill the axes.
        self.transWedge = mtransforms.BboxTransformFrom(self.axesLim)

        # Scale the axes to fill the figure.
        self.transAxes = mtransforms.BboxTransformTo(self.bbox)

        # A (possibly non-linear) projection on the (already scaled)
        # data.  This one is aware of rmin
        self.transProjection = self.PolarTransform(
            self, _apply_theta_transforms=False)
        # Add dependency on rorigin.
        self.transProjection.set_children(self._originViewLim)

        # An affine transformation on the data, generally to limit the
        # range of the axes
        self.transProjectionAffine = self.PolarAffine(self.transScale,
                                                      self._originViewLim)

        # The complete data transformation stack -- from data all the
        # way to display coordinates
        self.transData = (
            self.transScale + self.transShift + self.transProjection +
            (self.transProjectionAffine + self.transWedge + self.transAxes))

        # This is the transform for theta-axis ticks.  It is
        # equivalent to transData, except it always puts r == 0.0 and r == 1.0
        # at the edge of the axis circles.
        self._xaxis_transform = (mtransforms.blended_transform_factory(
            mtransforms.IdentityTransform(),
            mtransforms.BboxTransformTo(self.viewLim)) + self.transData)
        # The theta labels are flipped along the radius, so that text 1 is on
        # the outside by default. This should work the same as before.
        flipr_transform = mtransforms.Affine2D() \
            .translate(0.0, -0.5) \
            .scale(1.0, -1.0) \
            .translate(0.0, 0.5)
        self._xaxis_text_transform = flipr_transform + self._xaxis_transform

        # This is the transform for r-axis ticks.  It scales the theta
        # axis so the gridlines from 0.0 to 1.0, now go from thetamin to
        # thetamax.
        self._yaxis_transform = (mtransforms.blended_transform_factory(
            mtransforms.BboxTransformTo(self.viewLim),
            mtransforms.IdentityTransform()) + self.transData)
        # The r-axis labels are put at an angle and padded in the r-direction
        self._r_label_position = mtransforms.Affine2D() \
            .translate(self._default_rlabel_position, 0.0)
        self._yaxis_text_transform = mtransforms.TransformWrapper(
            self._r_label_position + self.transData)
Example #2
0
def rotation(rotation_degree):
    rot = transforms.Affine2D().rotate_deg(
        rotation_degree)  # make sure this matches in GUI
    return rot
Example #3
0
    def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
                    pivot, sizes, fill_empty, flip):
        """
        Create the wind barbs.

        Parameters
        ----------
        u, v
            Components of the vector in the x and y directions, respectively.

        nflags, nbarbs, half_barb, empty_flag
            Respectively, the number of flags, number of barbs, flag for
            half a barb, and flag for empty barb, ostensibly obtained from
            :meth:`_find_tails`.

        length
            The length of the barb staff in points.

        pivot : {"tip", "middle"} or number
            The point on the barb around which the entire barb should be
            rotated.  If a number, the start of the barb is shifted by that
            many points from the origin.

        sizes : dict
            Coefficients specifying the ratio of a given feature to the length
            of the barb. These features include:

            - *spacing*: space between features (flags, full/half barbs).
            - *height*: distance from shaft of top of a flag or full barb.
            - *width*: width of a flag, twice the width of a full barb.
            - *emptybarb*: radius of the circle used for low magnitudes.

        fill_empty : bool
            Whether the circle representing an empty barb should be filled or
            not (this changes the drawing of the polygon).

        flip : list of bool
            Whether the features should be flipped to the other side of the
            barb (useful for winds in the southern hemisphere).

        Returns
        -------
        list of arrays of vertices
            Polygon vertices for each of the wind barbs.  These polygons have
            been rotated to properly align with the vector direction.
        """

        # These control the spacing and size of barb elements relative to the
        # length of the shaft
        spacing = length * sizes.get('spacing', 0.125)
        full_height = length * sizes.get('height', 0.4)
        full_width = length * sizes.get('width', 0.25)
        empty_rad = length * sizes.get('emptybarb', 0.15)

        # Controls y point where to pivot the barb.
        pivot_points = dict(tip=0.0, middle=-length / 2.)

        endx = 0.0
        try:
            endy = float(pivot)
        except ValueError:
            endy = pivot_points[pivot.lower()]

        # Get the appropriate angle for the vector components.  The offset is
        # due to the way the barb is initially drawn, going down the y-axis.
        # This makes sense in a meteorological mode of thinking since there 0
        # degrees corresponds to north (the y-axis traditionally)
        angles = -(ma.arctan2(v, u) + np.pi / 2)

        # Used for low magnitude.  We just get the vertices, so if we make it
        # out here, it can be reused.  The center set here should put the
        # center of the circle at the location(offset), rather than at the
        # same point as the barb pivot; this seems more sensible.
        circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
        if fill_empty:
            empty_barb = circ
        else:
            # If we don't want the empty one filled, we make a degenerate
            # polygon that wraps back over itself
            empty_barb = np.concatenate((circ, circ[::-1]))

        barb_list = []
        for index, angle in np.ndenumerate(angles):
            # If the vector magnitude is too weak to draw anything, plot an
            # empty circle instead
            if empty_flag[index]:
                # We can skip the transform since the circle has no preferred
                # orientation
                barb_list.append(empty_barb)
                continue

            poly_verts = [(endx, endy)]
            offset = length

            # Handle if this barb should be flipped
            barb_height = -full_height if flip[index] else full_height

            # Add vertices for each flag
            for i in range(nflags[index]):
                # The spacing that works for the barbs is a little to much for
                # the flags, but this only occurs when we have more than 1
                # flag.
                if offset != length:
                    offset += spacing / 2.
                poly_verts.extend(
                    [[endx, endy + offset],
                     [endx + barb_height, endy - full_width / 2 + offset],
                     [endx, endy - full_width + offset]])

                offset -= full_width + spacing

            # Add vertices for each barb.  These really are lines, but works
            # great adding 3 vertices that basically pull the polygon out and
            # back down the line
            for i in range(nbarbs[index]):
                poly_verts.extend(
                    [(endx, endy + offset),
                     (endx + barb_height, endy + offset + full_width / 2),
                     (endx, endy + offset)])

                offset -= spacing

            # Add the vertices for half a barb, if needed
            if half_barb[index]:
                # If the half barb is the first on the staff, traditionally it
                # is offset from the end to make it easy to distinguish from a
                # barb with a full one
                if offset == length:
                    poly_verts.append((endx, endy + offset))
                    offset -= 1.5 * spacing
                poly_verts.extend(
                    [(endx, endy + offset),
                     (endx + barb_height / 2, endy + offset + full_width / 4),
                     (endx, endy + offset)])

            # Rotate the barb according the angle. Making the barb first and
            # then rotating it made the math for drawing the barb really easy.
            # Also, the transform framework makes doing the rotation simple.
            poly_verts = transforms.Affine2D().rotate(-angle).transform(
                poly_verts)
            barb_list.append(poly_verts)

        return barb_list
 def __init__(self, aux_transform):
     AuxTransformBox.__init__(self, aux_transform)
     self.dpi_transform = mtransforms.Affine2D()
Example #5
0
xyo = list(zip(xo, yo))

# Make a list of colors cycling through the default series.
colors = [
    colors.to_rgba(c)
    for c in plt.rcParams['axes.prop_cycle'].by_key()['color']
]

fig, axes = plt.subplots(2, 2)
fig.subplots_adjust(top=0.92, left=0.07, right=0.97, hspace=0.3, wspace=0.3)
((ax1, ax2), (ax3, ax4)) = axes  # unpack the axes

col = collections.LineCollection([spiral],
                                 offsets=xyo,
                                 transOffset=ax1.transData)
trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0 / 72.0)
col.set_transform(trans)  # the points to pixels transform
# Note: the first argument to the collection initializer
# must be a list of sequences of x,y tuples; we have only
# one sequence, but we still have to put it in a list.
ax1.add_collection(col, autolim=True)
# autolim=True enables autoscaling.  For collections with
# offsets like this, it is neither efficient nor accurate,
# but it is good enough to generate a plot that you can use
# as a starting point.  If you know beforehand the range of
# x and y that you want to show, it is better to set them
# explicitly, leave out the autolim kwarg (or set it to False),
# and omit the 'ax1.autoscale_view()' call below.

# Make a transform for the line segments such that their size is
# given in points:
def test_total(num_poly=10, num_knots=4, noise=0.1, smooth=False):
    '''
    Function that performs transformation between x, y and xref yref then fits that difference using polynomial fit followed by spline
    num_poly is the number of polynomial terms used, 10 gets all quadratic terms
    num_knots is th enumber of knots in the slpine along each axis, that is 4 means there is a total of 16 knots 
    noise is the sigma (in pixels) used to 
    '''


    xref = np.random.rand(10000) * 4096 - 2048
    yref = np.random.rand(10000) * 4096 - 2048 


    '''
    these star lists will be put through both the known tranformation (rotation and translation) and also put through the derived polynomial and spline fits as a check
    '''
    x_dim_ref = np.random.rand(1000) * 4096 - 2048
    y_dim_ref = np.random.rand(1000) * 4096 - 2048 

     
    
    trans = transforms.Affine2D()
    trans.rotate_deg(75.0)
    trans.translate(184, -45)
    
    cooref = np.array([xref, yref]).T
    
    coo1 = trans.transform(cooref) 
    coo_dim = trans.transform(np.array([x_dim_ref,y_dim_ref]).T)
    
    x_dim1 = coo_dim[:,0] + noise*np.random.randn(len(x_dim_ref))
    y_dim1 = coo_dim[:,1] + noise*np.random.randn(len(y_dim_ref))
    
    x1 = coo1[:,0] + noise*np.random.randn(len(xref))
    y1 = coo1[:,1] + noise*np.random.randn(len(yref))

    c_x, c_y = high_order.fit_poly(x1, y1, xref,  yref, num_poly)

    x_poly = high_order.poly(np.array([x1,y1]), c_x)
    y_poly = high_order.poly(np.array([x1,y1]), c_y)

    #if np.sum(np.abs(x_poly-xref)) < 1 and  np.sum(np.abs(y_poly-yref)) < len(xref):
    #    print 'Polynomial Fit was sufficient'
    #    return  c_x, c_y

    
    '''
    Now do spline fit between the polynomial fit and reference, to get rid of residual
    '''

    dx_sp, spline_dx = high_order.fit_spline(x_poly, y_poly, xref-x_poly, num_knots=num_knots, smooth=smooth)
    dy_sp, spline_dy = high_order.fit_spline(x_poly, y_poly, yref-y_poly, num_knots=num_knots, smooth=smooth)

    x_sp, spline_x = high_order.fit_spline(x_poly, y_poly, xref, num_knots=num_knots, smooth=smooth)
    y_sp, spline_y = high_order.fit_spline(x_poly, y_poly, yref, num_knots=num_knots, smooth=smooth)

    
    assert np.sum(np.abs(x_sp-(x_poly+dx_sp)))/len(x_poly) < noise
    assert np.sum(np.abs(y_sp-(y_poly+dy_sp)))/len(y_poly) < noise

    assert np.sum(np.abs(x_sp - xref))/len(x_sp) < noise
    assert np.sum(np.abs(y_sp - yref))/len(y_sp) < noise

    x_dim_poly = high_order.poly(np.array([x_dim1,y_dim1]), c_x)
    y_dim_poly = high_order.poly(np.array([x_dim1,y_dim1]), c_y)

    assert np.sum(np.abs(x_dim_poly - x_dim_ref)) / len(x_dim_ref) < noise
    assert np.sum(np.abs(y_dim_poly - y_dim_ref)) / len(y_dim_ref) < noise

    x_dim_sp = spline_x.ev(x_dim_poly, y_dim_poly)
    y_dim_sp = spline_y.ev(x_dim_poly,y_dim_poly)

    assert np.sum(np.abs(x_dim_sp - x_dim_ref)) / len(x_dim_ref) < noise
    assert np.sum(np.abs(y_dim_sp - y_dim_ref)) / len(y_dim_ref) < noise

    
    
    
    return x_sp, y_sp, xref, yref, spline_x, spline_y , c_x, c_y, x1, y1
Example #7
0
from __future__ import division
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.transforms as mtransforms
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

def draw_object(ax, transformation):
    dish = mpatches.Ellipse([0, 0], 3, 5, ec='k', fc='none', transform=transformation)
    #rod = mlines.Line2D([0, 10], [0, 0], color='k', transform=transformation)
    antenna = mpatches.Circle([10, 0], 1, ec='k', fc='none', transform=transformation)
    ax.add_patch(dish)
    #ax.add_patch(rod)
    ax.add_patch(antenna)

if __name__ == '__main__':
    fig, ax = plt.subplots()
    NoTransform = mtransforms.Affine2D(np.identity(3))
    draw_object(ax, NoTransform)
    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20)
    ax.set_aspect('equal')
    plt.show()
Example #8
0
 def draw_update(self, axes):
     self.drawings[0][0].center = (self.x[0], self.x[1])
     self.drawings[1][0].center = (self.x[0], self.x[1])
     tr = transforms.Affine2D().translate(self.x[0], self.x[1])
     self.drawings[0][1].set_transform(tr + axes[0].transData)
    def confidence_ellipse(self, j, n_std=1.0, edgecolor='k', linestyle='-', **kwargs):
        # """
        # Create a plot of the covariance confidence ellipse of *x* and *y*.
        #
        # Parameters
        # ----------
        # j : joint  probability  table
        #     Input data.
        #
        # ax : matplotlib.axes.Axes
        #     The axes object to draw the ellipse into.
        #
        # n_std : float
        #     The number of standard deviations to determine the ellipse's radiuses.
        #
        # **kwargs
        #     Forwarded to `~matplotlib.patches.Ellipse`
        #
        # Returns
        # -------
        # matplotlib.patches.Ellipse
        # """

        EX = np.dot(np.sum(j,1),np.arange(5));
        EX2 = np.dot(np.sum(j,1),[0,1,4,9,16]);
        EY = np.dot(np.sum(j,0),np.arange(5));
        EY2 = np.dot(np.sum(j,0),[0,1,4,9,16]);
        EXY = sum([j[x,y]*x*y for x in range(5) for y in range(5)])

        cov = np.zeros((2,2))
        cov[0,0] = EX2 - pow(EX,2)
        cov[1,1] = EY2 - pow(EY,2)
        cov[0,1] = EXY - EX*EY
        cov[1,0]  = cov[0,1]
        # if x.size != y.size:
        #     raise ValueError("x and y must be the same size")
        #
        # cov = np.cov(x, y)
        if cov[0,0] < 1e-3 or cov[1, 1] < 1e-3:
            return
        pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])
        # Using a special case to obtain the eigenvalues of this
        # two-dimensionl dataset.
        ell_radius_x = np.sqrt(1 + pearson)
        ell_radius_y = np.sqrt(1 - pearson)
        ellipse = Ellipse((0,0), width=ell_radius_x * 2, height=ell_radius_y * 2,
                          facecolor='none', edgecolor=edgecolor,linestyle=linestyle, **kwargs)

        # Calculating the stdandard deviation of x from
        # the squareroot of the variance and multiplying
        # with the given number of standard deviations.
        scale_x = np.sqrt(cov[0, 0]) * n_std
        mean_x = EX

        # calculating the stdandard deviation of y ...
        scale_y = np.sqrt(cov[1, 1]) * n_std
        mean_y = EY

        transf = transforms.Affine2D() \
            .rotate_deg(45) \
            .scale(scale_x, scale_y) \
            .translate(mean_x, mean_y)

        ellipse.set_transform(transf + self.ax.transData)
        self.ax.add_patch(ellipse)
        return
    regr.fit(np.array([x[train_ix], y[train_ix]]).T, eu[train_ix])
    pred = regr.predict(np.array([x[test_ix], y[test_ix]]).T)

    y_var = np.zeros([50, len(x[test_ix])])
    for j in range(50):
        y_var[j, :] = regr.estimators_[j].predict(
            np.array([x[test_ix], y[test_ix]]).T)

    aqf = pred + np.var(y_var, axis=0)
    ix = np.where(aqf == np.max(aqf))[0]
    i = np.random.choice(ix)

    train_ix.append(test_ix.pop(i))

#show which points were selected
rot = transforms.Affine2D().rotate_deg(-90)
plt.figure(figsize=(10, 11.4))
base = plt.gca().transData
plt.scatter(x, y, c=eu, transform=rot + base, cmap='Greys', label='Map data')
plt.plot(x[train_ix],
         y[train_ix],
         '-o',
         transform=rot + base,
         color='red',
         alpha=0.5,
         label='Selected points')
#plt.scatter(x[train_ix],y[train_ix],c=eu[train_ix],transform=rot+base)
plt.axis('equal')
plt.axis('off')
plt.legend(frameon=False)
# |-----

# |-------------------------------------------------------------

#C# Transforms

# |-------------------------------------------------------------
#T# the transforms module of the matplotlib package is used to do transformations of a plot
import matplotlib.transforms as mtransforms

#T# transformations can be made via the methods of Affine2D objects created with the Affine2D constructor

# SYNTAX mtransforms.Affine2D(array1)
#T# array1 is an array containing the 3x3 transformation matrix, if omitted the default is the identity matrix, the returned Affine2D object consists of a transformation matrix

transformation1 = mtransforms.Affine2D([[3, 4, 1], [2, 5, 91], [15, 65, 2]])

#T# transformations can affect a given coordinate system, for this, the transformation and the coordinate system are added together, making sure to add the coordinate system last, because this addition is not commutative
transformation1 = mtransforms.Affine2D([[3, 4, 1], [2, 5, 91], [15, 65, 2]])
transformation2 = transformation1 + ax1.transData
transformation2 = transformation1 + ax1.transAxes

#T# the get_matrix function returns the transformation matrix of an Affine2D object
transformation1 = mtransforms.Affine2D([[3, 4, 1], [2, 5, 91], [15, 65, 2]])
arr1 = transformation1.get_matrix()  # [[3, 4, 1], [2, 5, 91], [15, 65, 2]]

#T# the set_matrix function sets the transformation matrix of an Affine2D object
transformation1 = mtransforms.Affine2D()
transformation1.set_matrix([[4, 5, 6], [2, 4, 6], [5, 50, 500]])

#T# the clear function makes the transformation matrix of an Affine2D object to be the identity matrix
Example #12
0
import numpy
from matplotlib import pyplot, transforms

data = numpy.random.randn(100)

vec_x = numpy.arange(0, -10, -0.1)
vec_y = numpy.sin(vec_x * -1)  # * numpy.pi / 180.)

print data
print vec_x
print vec_y

# first of all, the base transformation of the data points is needed
base = pyplot.gca().transData
print(type(base))
rot = transforms.Affine2D().rotate_deg(270)
print(type(rot))

# define transformed line
# line = pyplot.plot(data, 'r--', transform= rot + base)
# line = pyplot.plot(vec_x, vec_y)
line = pyplot.plot(vec_x, vec_y, 'r--', transform=rot + base)
# or alternatively, use:
# line.set_transform(rot + base)

pyplot.show()
Example #13
0
def confidence_ellipse(ax,
                       cov=None,
                       x=None,
                       y=None,
                       n_std=3.0,
                       facecolor='none',
                       **kwargs):
    """
    Create a plot of the covariance confidence ellipse of *x* and *y*.

    Parameters
    ----------

    cov : array
        The covariance matrix

    ax : matplotlib.axes.Axes
        The axes object to draw the ellipse into.

    n_std : float
        The number of standard deviations to determine the ellipse's radiuses.

    **kwargs
        Forwarded to `~matplotlib.patches.Ellipse`

    Returns
    -------
    matplotlib.patches.Ellipse
    """
    if cov is None:

        if x.size != y.size:
            raise ValueError("x and y must be the same size")

        cov = np.cov(x, y)

        mean_x = np.mean(x)
        mean_y = np.mean(y)

    else:

        mean_x = 0
        mean_y = 0

    pearson = cov[0, 1] / np.sqrt(cov[0, 0] * cov[1, 1])
    # Using a special case to obtain the eigenvalues of this
    # two-dimensionl dataset.
    ell_radius_x = np.sqrt(1 + pearson)
    ell_radius_y = np.sqrt(1 - pearson)
    ellipse = Ellipse((0, 0),
                      width=ell_radius_x * 2,
                      height=ell_radius_y * 2,
                      facecolor=facecolor,
                      **kwargs)

    # Calculating the stdandard deviation of x from
    # the squareroot of the variance and multiplying
    # with the given number of standard deviations.
    scale_x = np.sqrt(cov[0, 0]) * n_std

    # calculating the stdandard deviation of y ...
    scale_y = np.sqrt(cov[1, 1]) * n_std

    transf = transforms.Affine2D() \
        .rotate_deg(45) \
        .scale(scale_x, scale_y) \
        .translate(mean_x, mean_y)

    ellipse.set_transform(transf + ax.transData)
    return ax.add_patch(ellipse)

# prepare image and figure
fig, (ax2) = plt.subplots(1, 1)

Z1 = get_image(0, 2. * np.pi, 0, 4. * np.pi / np.sqrt(3))
Z2 = get_image(-2. * np.pi, 0, -2. * np.pi / np.sqrt(3), 0)
Z3 = get_image(-2. * np.pi, 0, -6. * np.pi / np.sqrt(3), 0)
Z4 = get_image(0, 2. * np.pi, -4. * np.pi / np.sqrt(3), 0)

# image rotation
#do_plot(ax1, Z1, mtransforms.Affine2D().rotate_deg(0),  [0, 2.*np.pi, 0, 2.*np.pi /np.sqrt(3)])

# image skew
a = 0
b = 15
do_plot(ax2, Z1,
        mtransforms.Affine2D().skew_deg(a, b),
        [0, 2. * np.pi, 0, 6. * np.pi / np.sqrt(3)])
do_plot(ax2, Z1,
        mtransforms.Affine2D().skew_deg(a, b),
        [-2. * np.pi, 0, 0, 6. * np.pi / np.sqrt(3)])
do_plot(ax2, Z3,
        mtransforms.Affine2D().skew_deg(a, b),
        [-2. * np.pi, 0, -6. * np.pi / np.sqrt(3), 0])
do_plot(ax2, Z4,
        mtransforms.Affine2D().skew_deg(a, b),
        [0, 2. * np.pi, -6. * np.pi / np.sqrt(3), 0])

#plt.show()
Example #15
0
def symbols(x, y, symbols, size, axes=None, units='inches'):
    """
    Draws fixed-size symbols.

    See :mod:`iris.symbols` for available symbols.

    Args:

    * x: iterable
        The x coordinates where the symbols will be plotted.

    * y: iterable
        The y coordinates where the symbols will be plotted.

    * symbols: iterable
        The symbols (from :mod:`iris.symbols`) to plot.

    * size: float
        The symbol size in `units`.

    Kwargs:

    * axes: the :class:`matplotlib.axes.Axes` to use for drawing.
        Defaults to the current axes if none provided.

    * units: ['inches', 'points']
        The unit for the symbol size.

    """
    if axes is None:
        axes = plt.gca()

    offsets = np.array(list(zip(x, y)))

    # XXX "match_original" doesn't work ... so brute-force it instead.
    #   PatchCollection constructor ignores all non-style keywords when using
    #   match_original
    #   See matplotlib.collections.PatchCollection.__init__
    #   Specifically matplotlib/collections line 1053
    # pc = PatchCollection(symbols, offsets=offsets, transOffset=ax.transData,
    #                      match_original=True)
    facecolors = [p.get_facecolor() for p in symbols]
    edgecolors = [p.get_edgecolor() for p in symbols]
    linewidths = [p.get_linewidth() for p in symbols]

    pc = mpl_collections.PatchCollection(symbols, offsets=offsets,
                                         transOffset=axes.transData,
                                         facecolors=facecolors,
                                         edgecolors=edgecolors,
                                         linewidths=linewidths)

    if units == 'inches':
        scale = axes.figure.dpi
    elif units == 'points':
        scale = axes.figure.dpi / 72.0
    else:
        raise ValueError("Unrecognised units: '%s'" % units)
    pc.set_transform(mpl_transforms.Affine2D().scale(0.5 * size * scale))

    axes.add_collection(pc)
    axes.autoscale_view()
Example #16
0
def test_path_intersect_path(phi):
    # test for the range of intersection angles
    eps_array = [1e-5, 1e-8, 1e-10, 1e-12]

    transform = transforms.Affine2D().rotate(np.deg2rad(phi))

    # a and b intersect at angle phi
    a = Path([(-2, 0), (2, 0)])
    b = transform.transform_path(a)
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b touch at angle phi at (0, 0)
    a = Path([(0, 0), (2, 0)])
    b = transform.transform_path(a)
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are orthogonal and intersect at (0, 3)
    a = transform.transform_path(Path([(0, 1), (0, 3)]))
    b = transform.transform_path(Path([(1, 3), (0, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are collinear and intersect at (0, 3)
    a = transform.transform_path(Path([(0, 1), (0, 3)]))
    b = transform.transform_path(Path([(0, 5), (0, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # self-intersect
    assert a.intersects_path(a)

    # a contains b
    a = transform.transform_path(Path([(0, 0), (5, 5)]))
    b = transform.transform_path(Path([(1, 1), (3, 3)]))
    assert a.intersects_path(b) and b.intersects_path(a)

    # a and b are collinear but do not intersect
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(3, 0), (3, 3)]))
    assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line but do not intersect
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(0, 6), (0, 7)]))
    assert not a.intersects_path(b) and not b.intersects_path(a)

    # Note: 1e-13 is the absolute tolerance error used for
    # `isclose` function from src/_path.h

    # a and b are parallel but do not touch
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line but do not intersect (really close)
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))
        assert not a.intersects_path(b) and not b.intersects_path(a)

    # a and b are on the same line and intersect (really close)
    for eps in eps_array:
        a = transform.transform_path(Path([(0, 1), (0, 5)]))
        b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))
        assert a.intersects_path(b) and b.intersects_path(a)

    # b is the same as a but with an extra point
    a = transform.transform_path(Path([(0, 1), (0, 5)]))
    b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))
    assert a.intersects_path(b) and b.intersects_path(a)
Example #17
0
 def _offset_transform(self, renderer):
     """Apply the offset to the given transform."""
     return mtransforms.Affine2D().translate(
         *map(renderer.points_to_pixels, self._offset))
Example #18
0
    def __init__(self,
                 transform,
                 label_x,
                 label_y,
                 length=0.15,
                 fontsize=0.08,
                 loc=2,
                 angle=0,
                 aspect_ratio=1,
                 pad=0.4,
                 borderpad=0.4,
                 frameon=False,
                 color='w',
                 alpha=1,
                 sep_x=0.01,
                 sep_y=0,
                 fontproperties=None,
                 back_length=0.15,
                 head_width=10,
                 head_length=15,
                 tail_width=2,
                 text_props=None,
                 arrow_props=None,
                 **kwargs):
        """
        Draw two perpendicular arrows to indicate directions.

        Parameters
        ----------
        transform : `matplotlib.transforms.Transform`
            The transformation object for the coordinate system in use, i.e.,
            :attr:`matplotlib.axes.Axes.transAxes`.

        label_x, label_y : str
            Label text for the x and y arrows

        length : float, default: 0.15
            Length of the arrow, given in coordinates of *transform*.

        fontsize : float, default: 0.08
            Size of label strings, given in coordinates of *transform*.

        loc : int, default: 2
            Location of the direction arrows. Valid location codes are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4,
                'right'        : 5,
                'center left'  : 6,
                'center right' : 7,
                'lower center' : 8,
                'upper center' : 9,
                'center'       : 10

        angle : float, default: 0
            The angle of the arrows in degrees.

        aspect_ratio : float, default: 1
            The ratio of the length of arrow_x and arrow_y.
            Negative numbers can be used to change the direction.

        pad : float, default: 0.4
            Padding around the labels and arrows, in fraction of the font size.

        borderpad : float, default: 0.4
            Border padding, in fraction of the font size.

        frameon : bool, default: False
            If True, draw a box around the arrows and labels.

        color : str, default: 'white'
            Color for the arrows and labels.

        alpha : float, default: 1
            Alpha values of the arrows and labels

        sep_x, sep_y : float, default: 0.01 and 0 respectively
            Separation between the arrows and labels in coordinates of
            *transform*.

        fontproperties : `matplotlib.font_manager.FontProperties`, optional
            Font properties for the label text.

        back_length : float, default: 0.15
            Fraction of the arrow behind the arrow crossing.

        head_width : float, default: 10
            Width of arrow head, sent to ArrowStyle.

        head_length : float, default: 15
            Length of arrow head, sent to ArrowStyle.

        tail_width : float, default: 2
            Width of arrow tail, sent to ArrowStyle.

        text_props, arrow_props : dict
            Properties of the text and arrows, passed to
            `.textpath.TextPath` and `.patches.FancyArrowPatch`.

        **kwargs
            Keyworded arguments to pass to
            :class:`matplotlib.offsetbox.AnchoredOffsetbox`.

        Attributes
        ----------
        arrow_x, arrow_y : `matplotlib.patches.FancyArrowPatch`
            Arrow x and y

        text_path_x, text_path_y : `matplotlib.textpath.TextPath`
            Path for arrow labels

        p_x, p_y : `matplotlib.patches.PathPatch`
            Patch for arrow labels

        box : `matplotlib.offsetbox.AuxTransformBox`
            Container for the arrows and labels.

        Notes
        -----
        If *prop* is passed as a keyword argument, but *fontproperties* is
        not, then *prop* is be assumed to be the intended *fontproperties*.
        Using both *prop* and *fontproperties* is not supported.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> import numpy as np
        >>> from mpl_toolkits.axes_grid1.anchored_artists import (
        ...     AnchoredDirectionArrows)
        >>> fig, ax = plt.subplots()
        >>> ax.imshow(np.random.random((10, 10)))
        >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110')
        >>> ax.add_artist(arrows)
        >>> fig.show()

        Using several of the optional parameters, creating downward pointing
        arrow and high contrast text labels.

        >>> import matplotlib.font_manager as fm
        >>> fontprops = fm.FontProperties(family='monospace')
        >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South',
        ...                                  loc='lower left', color='k',
        ...                                  aspect_ratio=-1, sep_x=0.02,
        ...                                  sep_y=-0.01,
        ...                                  text_props={'ec':'w', 'fc':'k'},
        ...                                  fontproperties=fontprops)
        """
        if arrow_props is None:
            arrow_props = {}

        if text_props is None:
            text_props = {}

        arrowstyle = ArrowStyle("Simple",
                                head_width=head_width,
                                head_length=head_length,
                                tail_width=tail_width)

        if fontproperties is None and 'prop' in kwargs:
            fontproperties = kwargs.pop('prop')

        if 'color' not in arrow_props:
            arrow_props['color'] = color

        if 'alpha' not in arrow_props:
            arrow_props['alpha'] = alpha

        if 'color' not in text_props:
            text_props['color'] = color

        if 'alpha' not in text_props:
            text_props['alpha'] = alpha

        t_start = transform
        t_end = t_start + transforms.Affine2D().rotate_deg(angle)

        self.box = AuxTransformBox(t_end)

        length_x = length
        length_y = length * aspect_ratio

        self.arrow_x = FancyArrowPatch((0, back_length * length_y),
                                       (length_x, back_length * length_y),
                                       arrowstyle=arrowstyle,
                                       shrinkA=0.0,
                                       shrinkB=0.0,
                                       **arrow_props)

        self.arrow_y = FancyArrowPatch((back_length * length_x, 0),
                                       (back_length * length_x, length_y),
                                       arrowstyle=arrowstyle,
                                       shrinkA=0.0,
                                       shrinkB=0.0,
                                       **arrow_props)

        self.box.add_artist(self.arrow_x)
        self.box.add_artist(self.arrow_y)

        text_path_x = TextPath(
            (length_x + sep_x, back_length * length_y + sep_y),
            label_x,
            size=fontsize,
            prop=fontproperties)
        self.p_x = PathPatch(text_path_x, transform=t_start, **text_props)
        self.box.add_artist(self.p_x)

        text_path_y = TextPath((length_x * back_length + sep_x, length_y *
                                (1 - back_length) + sep_y),
                               label_y,
                               size=fontsize,
                               prop=fontproperties)
        self.p_y = PathPatch(text_path_y, **text_props)
        self.box.add_artist(self.p_y)

        super().__init__(loc,
                         pad=pad,
                         borderpad=borderpad,
                         child=self.box,
                         frameon=frameon,
                         **kwargs)
Example #19
0
 def set_transform(self, transform):
     # 2 pixel offset
     texttrans = transform + mtransforms.Affine2D().translate(2, 2)
     self.text.set_transform(texttrans)
     lines.Line2D.set_transform(self, transform)
Example #20
0
    def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
                    pivot, sizes, fill_empty, flip):
        '''
        This function actually creates the wind barbs.  *u* and *v*
        are components of the vector in the *x* and *y* directions,
        respectively.

        *nflags*, *nbarbs*, and *half_barb*, empty_flag* are,
        *respectively, the number of flags, number of barbs, flag for
        *half a barb, and flag for empty barb, ostensibly obtained
        *from :meth:`_find_tails`.

        *length* is the length of the barb staff in points.

        *pivot* specifies the point on the barb around which the
        entire barb should be rotated.  Right now, valid options are
        'head' and 'middle'.

        *sizes* is a dictionary of coefficients specifying the ratio
        of a given feature to the length of the barb. These features
        include:

            - *spacing*: space between features (flags, full/half
               barbs)

            - *height*: distance from shaft of top of a flag or full
               barb

            - *width* - width of a flag, twice the width of a full barb

            - *emptybarb* - radius of the circle used for low
               magnitudes

        *fill_empty* specifies whether the circle representing an
        empty barb should be filled or not (this changes the drawing
        of the polygon).

        *flip* is a flag indicating whether the features should be flipped to
        the other side of the barb (useful for winds in the southern
        hemisphere.

        This function returns list of arrays of vertices, defining a polygon for
        each of the wind barbs.  These polygons have been rotated to properly
        align with the vector direction.
        '''

        #These control the spacing and size of barb elements relative to the
        #length of the shaft
        spacing = length * sizes.get('spacing', 0.125)
        full_height = length * sizes.get('height', 0.4)
        full_width = length * sizes.get('width', 0.25)
        empty_rad = length * sizes.get('emptybarb', 0.15)

        #Controls y point where to pivot the barb.
        pivot_points = dict(tip=0.0, middle=-length / 2.)

        #Check for flip
        if flip: full_height = -full_height

        endx = 0.0
        endy = pivot_points[pivot.lower()]

        #Get the appropriate angle for the vector components.  The offset is due
        #to the way the barb is initially drawn, going down the y-axis.  This
        #makes sense in a meteorological mode of thinking since there 0 degrees
        #corresponds to north (the y-axis traditionally)
        angles = -(ma.arctan2(v, u) + np.pi / 2)

        #Used for low magnitude.  We just get the vertices, so if we make it
        #out here, it can be reused.  The center set here should put the
        #center of the circle at the location(offset), rather than at the
        #same point as the barb pivot; this seems more sensible.
        circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
        if fill_empty:
            empty_barb = circ
        else:
            #If we don't want the empty one filled, we make a degenerate polygon
            #that wraps back over itself
            empty_barb = np.concatenate((circ, circ[::-1]))

        barb_list = []
        for index, angle in np.ndenumerate(angles):
            #If the vector magnitude is too weak to draw anything, plot an
            #empty circle instead
            if empty_flag[index]:
                #We can skip the transform since the circle has no preferred
                #orientation
                barb_list.append(empty_barb)
                continue

            poly_verts = [(endx, endy)]
            offset = length

            #Add vertices for each flag
            for i in range(nflags[index]):
                #The spacing that works for the barbs is a little to much for
                #the flags, but this only occurs when we have more than 1 flag.
                if offset != length: offset += spacing / 2.
                poly_verts.extend(
                    [[endx, endy + offset],
                     [endx + full_height, endy - full_width / 2 + offset],
                     [endx, endy - full_width + offset]])

                offset -= full_width + spacing

            #Add vertices for each barb.  These really are lines, but works
            #great adding 3 vertices that basically pull the polygon out and
            #back down the line
            for i in range(nbarbs[index]):
                poly_verts.extend([(endx, endy + offset),
                                   (endx + full_height,
                                    endy + offset + full_width / 2),
                                   (endx, endy + offset)])

                offset -= spacing

            #Add the vertices for half a barb, if needed
            if half_barb[index]:
                #If the half barb is the first on the staff, traditionally it is
                #offset from the end to make it easy to distinguish from a barb
                #with a full one
                if offset == length:
                    poly_verts.append((endx, endy + offset))
                    offset -= 1.5 * spacing
                poly_verts.extend([(endx, endy + offset),
                                   (endx + full_height / 2,
                                    endy + offset + full_width / 4),
                                   (endx, endy + offset)])

            #Rotate the barb according the angle. Making the barb first and then
            #rotating it made the math for drawing the barb really easy.  Also,
            #the transform framework makes doing the rotation simple.
            poly_verts = transforms.Affine2D().rotate(-angle).transform(
                poly_verts)
            barb_list.append(poly_verts)

        return barb_list
Example #21
0
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

obs = [["01_S1", 3.88, 0.14, 1970, 63],
       ["01_S4", 5.6, 0.82, 1622, 150],
       ["02_S1", 2.4, 0.54, 1570, 40],
       ["03_S1", 4.1, 0.62, 2380, 170]]


fig = plt.figure()

ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)

# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5

aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")

fig.add_subplot(ax_kms)

for n, ds, dse, w, we in obs:
    time = ((2007 + (10. + 4/30.)/12) - 1988.5)
    v = ds / time * pm_to_kms
    ve = dse / time * pm_to_kms
    ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")


ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label(r"Proper Motion [$''$/yr]")
Example #22
0
 def __init__(self, *args, **kwargs):
     mtrans.Transform.__init__(self, *args, **kwargs)
     self.raise_on_transform = False
     self.underlying_transform = mtrans.Affine2D().scale(10, 10)
Example #23
0
 def _calc_offset_transform(self):
     """Calculate the offset transform performed by the spine."""
     self._ensure_position_is_set()
     position = self._position
     if isinstance(position, str):
         if position == 'center':
             position = ('axes', 0.5)
         elif position == 'zero':
             position = ('data', 0)
     assert len(position) == 2, "position should be 2-tuple"
     position_type, amount = position
     assert position_type in ('axes', 'outward', 'data')
     if position_type == 'outward':
         if amount == 0:
             # short circuit commonest case
             self._spine_transform = ('identity',
                                      mtransforms.IdentityTransform())
         elif self.spine_type in ['left', 'right', 'top', 'bottom']:
             offset_vec = {'left': (-1, 0),
                           'right': (1, 0),
                           'bottom': (0, -1),
                           'top': (0, 1),
                           }[self.spine_type]
             # calculate x and y offset in dots
             offset_x = amount * offset_vec[0] / 72.0
             offset_y = amount * offset_vec[1] / 72.0
             self._spine_transform = ('post',
                                      mtransforms.ScaledTranslation(
                                          offset_x,
                                          offset_y,
                                          self.figure.dpi_scale_trans))
         else:
             cbook._warn_external('unknown spine type "%s": no spine '
                                  'offset performed' % self.spine_type)
             self._spine_transform = ('identity',
                                      mtransforms.IdentityTransform())
     elif position_type == 'axes':
         if self.spine_type in ('left', 'right'):
             self._spine_transform = ('pre',
                                      mtransforms.Affine2D.from_values(
                                          # keep y unchanged, fix x at
                                          # amount
                                          0, 0, 0, 1, amount, 0))
         elif self.spine_type in ('bottom', 'top'):
             self._spine_transform = ('pre',
                                      mtransforms.Affine2D.from_values(
                                          # keep x unchanged, fix y at
                                          # amount
                                          1, 0, 0, 0, 0, amount))
         else:
             cbook._warn_external('unknown spine type "%s": no spine '
                                  'offset performed' % self.spine_type)
             self._spine_transform = ('identity',
                                      mtransforms.IdentityTransform())
     elif position_type == 'data':
         if self.spine_type in ('right', 'top'):
             # The right and top spines have a default position of 1 in
             # axes coordinates.  When specifying the position in data
             # coordinates, we need to calculate the position relative to 0.
             amount -= 1
         if self.spine_type in ('left', 'right'):
             self._spine_transform = ('data',
                                      mtransforms.Affine2D().translate(
                                          amount, 0))
         elif self.spine_type in ('bottom', 'top'):
             self._spine_transform = ('data',
                                      mtransforms.Affine2D().translate(
                                          0, amount))
         else:
             cbook._warn_external('unknown spine type "%s": no spine '
                                  'offset performed' % self.spine_type)
             self._spine_transform = ('identity',
                                      mtransforms.IdentityTransform())
Example #24
0
def test_transform_single_point():
    t = mtrans.Affine2D()
    r = t.transform_affine((1, 1))
    assert r.shape == (2, )
Example #25
0
 def _update_transform(self):
     self._shadow_transform = transforms.Affine2D().translate(self._ox, self._oy)
Example #26
0
 def _as_mpl_transform(self, axes):
     return mtrans.Affine2D().scale(self._scale_factor) + axes.transData
Example #27
0
    def draw_path_collection(self,
                             paths,
                             path_coordinates,
                             path_transforms,
                             offsets,
                             offset_coordinates,
                             offset_order,
                             styles,
                             mplobj=None):
        """
        Draw a collection of paths. The paths, offsets, and styles are all
        iterables, and the number of paths is max(len(paths), len(offsets)).

        By default, this is implemented via multiple calls to the draw_path()
        function. For efficiency, Renderers may choose to customize this
        implementation.

        Examples of path collections created by matplotlib are scatter plots,
        histograms, contour plots, and many others.

        Parameters
        ----------
        paths : list
            list of tuples, where each tuple has two elements:
            (data, pathcodes).  See draw_path() for a description of these.
        path_coordinates: string
            the coordinates code for the paths, which should be either
            'data' for data coordinates, or 'figure' for figure (pixel)
            coordinates.
        path_transforms: array_like
            an array of shape (*, 3, 3), giving a series of 2D Affine
            transforms for the paths. These encode translations, rotations,
            and scalings in the standard way.
        offsets: array_like
            An array of offsets of shape (N, 2)
        offset_coordinates : string
            the coordinates code for the offsets, which should be either
            'data' for data coordinates, or 'figure' for figure (pixel)
            coordinates.
        offset_order : string
            either "before" or "after". This specifies whether the offset
            is applied before the path transform, or after.  The matplotlib
            backend equivalent is "before"->"data", "after"->"screen".
        styles: dictionary
            A dictionary in which each value is a list of length N, containing
            the style(s) for the paths.
        mplobj : matplotlib object
            the matplotlib plot element which generated this collection
        """
        if offset_order == "before":
            raise NotImplementedError("offset before transform")

        for tup in self._iter_path_collection(paths, path_transforms, offsets,
                                              styles):
            (path, path_transform, offset, ec, lw, fc) = tup
            vertices, pathcodes = path
            path_transform = transforms.Affine2D(path_transform)
            vertices = path_transform.transform(vertices)
            # This is a hack:
            if path_coordinates == "figure":
                path_coordinates = "points"
            style = {
                "edgecolor": utils.color_to_hex(ec),
                "facecolor": utils.color_to_hex(fc),
                "edgewidth": lw,
                "dasharray": "10,0",
                "alpha": styles['alpha'],
                "zorder": styles['zorder']
            }
            self.draw_path(vertices,
                           path_coordinates,
                           pathcodes,
                           style,
                           offset,
                           offset_coordinates,
                           mplobj=mplobj)
def PyplotLinePolyCollection():
    import matplotlib.pyplot as plt
    from matplotlib import collections, colors, transforms
    import numpy as np

    nverts = 50
    npts = 100

    # Make some spirals
    r = np.arange(nverts)
    theta = np.linspace(0, 2 * np.pi, nverts)
    xx = r * np.sin(theta)
    yy = r * np.cos(theta)
    spiral = np.column_stack([xx, yy])

    # Fixing random state for reproducibility
    rs = np.random.RandomState(19680801)

    # Make some offsets
    xyo = rs.randn(npts, 2)

    # Make a list of colors cycling through the default series.
    colors = [
        colors.to_rgba(c)
        for c in plt.rcParams['axes.prop_cycle'].by_key()['color']
    ]

    fig, axes = plt.subplots(2, 2)
    fig.subplots_adjust(top=0.92,
                        left=0.07,
                        right=0.97,
                        hspace=0.3,
                        wspace=0.3)
    ((ax1, ax2), (ax3, ax4)) = axes  # unpack the axes

    col = collections.LineCollection([spiral],
                                     offsets=xyo,
                                     transOffset=ax1.transData)
    trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0 / 72.0)
    col.set_transform(trans)  # the points to pixels transform
    # Note: the first argument to the collection initializer
    # must be a list of sequences of x,y tuples; we have only
    # one sequence, but we still have to put it in a list.
    ax1.add_collection(col, autolim=True)
    # autolim=True enables autoscaling.  For collections with
    # offsets like this, it is neither efficient nor accurate,
    # but it is good enough to generate a plot that you can use
    # as a starting point.  If you know beforehand the range of
    # x and y that you want to show, it is better to set them
    # explicitly, leave out the autolim kwarg (or set it to False),
    # and omit the 'ax1.autoscale_view()' call below.

    # Make a transform for the line segments such that their size is
    # given in points:
    col.set_color(colors)

    ax1.autoscale_view()  # See comment above, after ax1.add_collection.
    ax1.set_title('LineCollection using offsets')

    # The same data as above, but fill the curves.
    col = collections.PolyCollection([spiral],
                                     offsets=xyo,
                                     transOffset=ax2.transData)
    trans = transforms.Affine2D().scale(fig.dpi / 72.0)
    col.set_transform(trans)  # the points to pixels transform
    ax2.add_collection(col, autolim=True)
    col.set_color(colors)

    ax2.autoscale_view()
    ax2.set_title('PolyCollection using offsets')

    # 7-sided regular polygons

    col = collections.RegularPolyCollection(7,
                                            sizes=np.abs(xx) * 10.0,
                                            offsets=xyo,
                                            transOffset=ax3.transData)
    trans = transforms.Affine2D().scale(fig.dpi / 72.0)
    col.set_transform(trans)  # the points to pixels transform
    ax3.add_collection(col, autolim=True)
    col.set_color(colors)
    ax3.autoscale_view()
    ax3.set_title('RegularPolyCollection using offsets')

    # Simulate a series of ocean current profiles, successively
    # offset by 0.1 m/s so that they form what is sometimes called
    # a "waterfall" plot or a "stagger" plot.

    nverts = 60
    ncurves = 20
    offs = (0.1, 0.0)

    yy = np.linspace(0, 2 * np.pi, nverts)
    ym = np.max(yy)
    xx = (0.2 + (ym - yy) / ym)**2 * np.cos(yy - 0.4) * 0.5
    segs = []
    for i in range(ncurves):
        xxx = xx + 0.02 * rs.randn(nverts)
        curve = np.column_stack([xxx, yy * 100])
        segs.append(curve)

    col = collections.LineCollection(segs, offsets=offs)
    ax4.add_collection(col, autolim=True)
    col.set_color(colors)
    ax4.autoscale_view()
    ax4.set_title('Successive data offsets')
    ax4.set_xlabel('Zonal velocity component (m/s)')
    ax4.set_ylabel('Depth (m)')
    # Reverse the y-axis so depth increases downward
    ax4.set_ylim(ax4.get_ylim()[::-1])
    return fig
Example #29
0
def animate(i):
    
    global p;
    global m;
    global z;

    currentTime = i * 0.1;
    drawnObjects = [];

    # Time
    txt.set_text("Time: {0}".format(currentTime));
    drawnObjects.append(txt);

    # Groundtruth 
    gtPoseCurrentPos.set_xdata(gtPose_x[i]);
    gtPoseCurrentPos.set_ydata(gtPose_y[i]); # Append to drawn objects later so it shows above measurements
    gtPoseHead = [gtPose_x[i] + 0.3*np.cos(gtPose_r[i]), gtPose_y[i] + 0.3*np.sin(gtPose_r[i]) ];
    gtPoseCurrentDir.set_xdata([gtPose_x[i], gtPoseHead[0]]);
    gtPoseCurrentDir.set_ydata([gtPose_y[i], gtPoseHead[1]]); # Append to drawn objects later so it shows above measurements

    # Particles
    p_idx = 0;
    p_idx_maxWeight = 0;
    p_maxWeight = p[5];
    px_best[i] = p[2];
    py_best[i] = p[3];
    p_x = [];
    p_y = [];
    p_w = [];
    while p.any() and abs(p[0] - currentTime) < 1e-12:
        p_x.append(p[2]);
        p_y.append(p[3]);
        p_w.append(p[5]);
        if p[5] > p_maxWeight :
            p_maxWeight = p[5];
            p_idx_maxWeight = p_idx;
            px_best[i] = p[2];
            py_best[i] = p[3];
        p = np.fromfile(estPoseFileHandle, dtype=float, count=6, sep=" ");
        p_idx += 1;
    particles.set_data(p_x, p_y);

    # Landmarks
    m_idx = 0;
    while m.any() and abs(m[0] - currentTime) < 1e-12:
        if round(m[1]) == round(p_idx_maxWeight):

            cov = np.array([ [ m[4], m[5] ], [ m[5], m[6] ] ]);
            w = m[7];
            eVal, eVec = np.linalg.eig(cov);
            eVal = eVal.real;
            a1 = 5*np.sqrt(eVal[0]); # Assume this is semi-major axis first
            a2 = 5*np.sqrt(eVal[1]); 
            semiMajorAxis = eVec[:,0];
            if a2 > a1:
                aTmp = a1
                a1 = a2
                a2 = aTmp
                semiMajorAxis = eVec[:,1];
            a1Angle = np.arctan2(semiMajorAxis[1], semiMajorAxis[0]);

            landmarks[m_idx].set_alpha(min(w, 0.75));
            landmarks[m_idx].center = (m[2], m[3]);
            landmarks[m_idx].height = a2;
            landmarks[m_idx].width = a1;
            t_start = ax.transData;
            t_rot = transforms.Affine2D().rotate_around(m[2], m[3], a1Angle);
            t_compound = t_rot + t_start;
            landmarks[m_idx].set_transform(t_compound);
            drawnObjects.append(landmarks[m_idx]);
            m_idx += 1;

        m = np.fromfile(estMapFileHandle, count=8, sep=" ", dtype=float);

    while landmarks[m_idx].height != 0:
        landmarks[m_idx].set_alpha(0);
        landmarks[m_idx].center = (0, 0);
        landmarks[m_idx].height = 0;
        landmarks[m_idx].width = 0;
        m_idx += 1;

    # Measurements
    nZ = 0;
    while z.any() and abs(z[0] -  currentTime) < 1e-12:
        z_dir = gtPose_r[i] + z[2];
        z_end = [gtPose_x[i] + z[1]*np.cos(z_dir), gtPose_y[i] + z[1]*np.sin(z_dir) ];
        measurements[nZ].set_data([gtPose_x[i], z_end[0]], [gtPose_y[i], z_end[1]]);
        drawnObjects.append(measurements[nZ]);
        z = np.fromfile(measurementFileHandle, count=3, sep=" ", dtype=float);
        nZ += 1;
    while measurements[nZ].get_xdata() != []:
        measurements[nZ].set_data([], []);
        nZ += 1;
    
    drawnObjects.append(gtPoseCurrentPos);
    drawnObjects.append(gtPoseCurrentDir);
    drawnObjects.append(particles);

    return drawnObjects;
Example #30
0
    def update_position(self, loc):
        super().update_position(loc)
        axes = self.axes
        thetamin = axes.get_thetamin()
        thetamax = axes.get_thetamax()
        direction = axes.get_theta_direction()
        offset_rad = axes.get_theta_offset()
        offset = np.rad2deg(offset_rad)
        full = _is_full_circle_deg(thetamin, thetamax)

        if full:
            angle = (axes.get_rlabel_position() * direction +
                     offset) % 360 - 90
            tick_angle = 0
        else:
            angle = (thetamin * direction + offset) % 360 - 90
            if direction > 0:
                tick_angle = np.deg2rad(angle)
            else:
                tick_angle = np.deg2rad(angle + 180)
        text_angle = (angle + 90) % 180 - 90  # between -90 and +90.
        mode, user_angle = self._labelrotation
        if mode == 'auto':
            text_angle += user_angle
        else:
            text_angle = user_angle

        if full:
            ha = self.label1.get_horizontalalignment()
            va = self.label1.get_verticalalignment()
        else:
            ha, va = self._determine_anchor(mode, angle, direction > 0)
        self.label1.set_horizontalalignment(ha)
        self.label1.set_verticalalignment(va)
        self.label1.set_rotation(text_angle)

        marker = self.tick1line.get_marker()
        if marker == mmarkers.TICKLEFT:
            trans = mtransforms.Affine2D().rotate(tick_angle)
        elif marker == '_':
            trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
        elif marker == mmarkers.TICKRIGHT:
            trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
        else:
            # Don't modify custom tick line markers.
            trans = self.tick1line._marker._transform
        self.tick1line._marker._transform = trans

        if full:
            self.label2.set_visible(False)
            self.tick2line.set_visible(False)
        angle = (thetamax * direction + offset) % 360 - 90
        if direction > 0:
            tick_angle = np.deg2rad(angle)
        else:
            tick_angle = np.deg2rad(angle + 180)
        text_angle = (angle + 90) % 180 - 90  # between -90 and +90.
        mode, user_angle = self._labelrotation
        if mode == 'auto':
            text_angle += user_angle
        else:
            text_angle = user_angle

        ha, va = self._determine_anchor(mode, angle, direction < 0)
        self.label2.set_ha(ha)
        self.label2.set_va(va)
        self.label2.set_rotation(text_angle)

        marker = self.tick2line.get_marker()
        if marker == mmarkers.TICKLEFT:
            trans = mtransforms.Affine2D().rotate(tick_angle)
        elif marker == '_':
            trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
        elif marker == mmarkers.TICKRIGHT:
            trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
        else:
            # Don't modify custom tick line markers.
            trans = self.tick2line._marker._transform
        self.tick2line._marker._transform = trans