Python matplotlib.patches.Ellipse() Examples

The following are code examples for showing how to use matplotlib.patches.Ellipse(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: LPFC   Author: myyim   File: lpfc_model.py    MIT License 7 votes vote down vote up
def cov_ellipse(points, nstd=1, ax=None, **kwargs):
    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    pos = points.mean(axis=0)
    cov = np.cov(points, rowvar=False)
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]        
    if ax is None:
        ax = plt.gca()
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)
    ax.add_artist(ellip)
    return pos 
Example 2
Project: b2ac   Author: hbldh   File: ellipse.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Ellipse
            from b2ac.ellipse import B2ACEllipse

            e = B2ACEllipse((3.0, 5.0), (2.0, 6.0, 1.57))
            plt.gca().add_patch(Ellipse(
                e.mpl_patch_arguments, fill=False, edgecolor='g'))
            plt.show()

        """
        return self.center_point, self.radii[0] * 2, self.radii[1] * 2, np.rad2deg(self.rotation_angle) 
Example 3
Project: scicast   Author: iandriver   File: dim_reduction.py    MIT License 6 votes vote down vote up
def ellip_enclose(points, color, inc=1, lw=2, nst=2):
    """
    Plot the minimum ellipse around a set of points.

    Based on:
    https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
    """

    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    x = points[:,0]
    y = points[:,1]
    cov = np.cov(x, y)
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    w, h = 2 * nst * np.sqrt(vals)
    center = np.mean(points, 0)
    ell = patches.Ellipse(center, width=inc*w, height=inc*h, angle=theta,
                          facecolor=color, alpha=0.2, lw=0)
    edge = patches.Ellipse(center, width=inc*w, height=inc*h, angle=theta,
                          facecolor='none', edgecolor=color, lw=lw)
    return ell, edge 
Example 4
Project: scicast   Author: iandriver   File: cluster.py    MIT License 6 votes vote down vote up
def ellip_enclose(points, color, inc=1, lw=2, nst=2):
    """
    Plot the minimum ellipse around a set of points.

    Based on:
    https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
    """

    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    x = points[:,0]
    y = points[:,1]
    cov = np.cov(x, y)
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    w, h = 2 * nst * np.sqrt(vals)
    center = np.mean(points, 0)
    ell = patches.Ellipse(center, width=inc*w, height=inc*h, angle=theta,
                          facecolor=color, alpha=0.2, lw=0)
    edge = patches.Ellipse(center, width=inc*w, height=inc*h, angle=theta,
                          facecolor='none', edgecolor=color, lw=lw)
    return ell, edge 
Example 5
Project: tf-example-models   Author: aakhundov   File: tf_gmm_tools.py    Apache License 2.0 6 votes vote down vote up
def _plot_gaussian(mean, covariance, color, zorder=0):
    """Plots the mean and 2-std ellipse of a given Gaussian"""
    plt.plot(mean[0], mean[1], color[0] + ".", zorder=zorder)

    if covariance.ndim == 1:
        covariance = np.diag(covariance)

    radius = np.sqrt(5.991)
    eigvals, eigvecs = np.linalg.eig(covariance)
    axis = np.sqrt(eigvals) * radius
    slope = eigvecs[1][0] / eigvecs[1][1]
    angle = 180.0 * np.arctan(slope) / np.pi

    plt.axes().add_artist(pat.Ellipse(
        mean, 2 * axis[0], 2 * axis[1], angle=angle,
        fill=False, color=color, linewidth=1, zorder=zorder
    )) 
Example 6
Project: tf-example-models   Author: aakhundov   File: utils.py    Apache License 2.0 6 votes vote down vote up
def _plot_gaussian(mean, covariance, color, zorder=0):
    """Plots the mean and 2-std ellipse of a given Gaussian"""
    plt.plot(mean[0], mean[1], color[0] + ".", zorder=zorder)

    if covariance.ndim == 1:
        covariance = np.diag(covariance)

    radius = np.sqrt(5.991)
    eigvals, eigvecs = np.linalg.eig(covariance)
    axis = np.sqrt(eigvals) * radius
    slope = eigvecs[1][0] / eigvecs[1][1]
    angle = 180.0 * np.arctan(slope) / np.pi

    plt.axes().add_artist(pat.Ellipse(
        mean, 2 * axis[0], 2 * axis[1], angle=angle,
        fill=False, color=color, linewidth=1, zorder=zorder
    )) 
Example 7
Project: tf-example-models   Author: aakhundov   File: tf_gmm.py    Apache License 2.0 6 votes vote down vote up
def plot_fitted_data(points, c_means, c_variances):
    """Plots the data and given Gaussian components"""
    plt.plot(points[:, 0], points[:, 1], "b.", zorder=0)
    plt.plot(c_means[:, 0], c_means[:, 1], "r.", zorder=1)

    for i in range(c_means.shape[0]):
        std = np.sqrt(c_variances[i])
        plt.axes().add_artist(pat.Ellipse(
            c_means[i], 2 * std[0], 2 * std[1],
            fill=False, color="red", linewidth=2, zorder=1
        ))

    plt.show()


# PREPARING DATA

# generating DATA_POINTS points from a GMM with COMPONENTS components 
Example 8
Project: vnpy_crypto   Author: birforce   File: plot_grids.py    MIT License 6 votes vote down vote up
def _make_ellipse(mean, cov, ax, level=0.95, color=None):
    """Support function for scatter_ellipse."""
    from matplotlib.patches import Ellipse

    v, w = np.linalg.eigh(cov)
    u = w[0] / np.linalg.norm(w[0])
    angle = np.arctan(u[1]/u[0])
    angle = 180 * angle / np.pi # convert to degrees
    v = 2 * np.sqrt(v * stats.chi2.ppf(level, 2)) #get size corresponding to level
    ell = Ellipse(mean[:2], v[0], v[1], 180 + angle, facecolor='none',
                  edgecolor=color,
                  #ls='dashed',  #for debugging
                  lw=1.5)
    ell.set_clip_box(ax.bbox)
    ell.set_alpha(0.5)
    ax.add_artist(ell) 
Example 9
Project: demos   Author: jnez71   File: resection_ekf.py    MIT License 6 votes vote down vote up
def plot_setup():
    global ellipse, estim_point, estim_head, conf, setup_calls
    setup_calls += 1
    if setup_calls == 1:
        ax.scatter(landmarks[:, 0], landmarks[:, 1], c='g', label="landmark")
        ax.scatter(state_true[0], state_true[1], c='b', label="truth")
        ax.quiver(state_true[0], state_true[1], np.cos(state_true[2]), np.sin(state_true[2]), color='b', scale=20, width=5e-3)
        for landmark, measurement in zip(landmarks, measurements):
            dist = npl.norm(landmark - state_true[:2])
            ang = unwrap(measurement + state_true[2])
            hit = state_true[:2] + [dist*np.cos(ang), dist*np.sin(ang)]
            ax.plot([state_true[0], hit[0]], [state_true[1], hit[1]], color='y', linewidth=1)
        ax.plot([0, 0], [0, 0], color='y', linewidth=1, label="measurement")
        estim_point = ax.scatter(prior_mean[0], prior_mean[1], c='r', label="estimate")
        estim_head = ax.quiver(prior_mean[0], prior_mean[1], np.cos(prior_mean[2]), np.sin(prior_mean[2]), color='r', scale=20, width=5e-3)
        conf = 2*np.sqrt(6)
        evals, evecs = npl.eigh(prior_covar[:2, :2])
        ellipse = Ellipse(xy=prior_mean, width=conf*np.sqrt(evals[-1]), height=conf*np.sqrt(evals[0]),
                          angle=np.rad2deg(np.arctan2(evecs[1, -1], evecs[0, -1])),
                          edgecolor='r', lw=1, facecolor='none')
        ax.add_artist(ellipse)
        ax.plot([0, 0], [0, 0], color='r', linewidth=2, label="95% confidence")
        ax.legend(loc=2)
    return [] 
Example 10
Project: ad_examples   Author: shubhomoydas   File: gmm_outlier.py    MIT License 6 votes vote down vote up
def make_ellipses(gmm, pl, colors):
    covariances = None
    for k in range(gmm.n_components):
        color = colors[k]
        # logger.debug("color: %s" % color)
        if gmm.covariance_type == 'full':
            covariances = gmm.covariances_[k][:2, :2]
        elif gmm.covariance_type == 'tied':
            covariances = gmm.covariances_[:2, :2]
        elif gmm.covariance_type == 'diag':
            covariances = np.diag(gmm.covariances_[k][:2])
        elif gmm.covariance_type == 'spherical':
            covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[k]
        # find the ellipse size and orientation w.r.t largest eigen value
        v, w = np.linalg.eigh(covariances)
        u = w[0] / np.linalg.norm(w[0])  # normalize direction of largest eigen value
        angle = np.arctan2(u[1], u[0])  # find direction of the vector with largest eigen value
        angle = 180 * angle / np.pi  # convert to degrees
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        ell = Ellipse(xy=gmm.means_[k, :2], width=v[0], height=v[1], angle=180 + angle,
                      edgecolor=color, facecolor='none', linewidth=2)
        ell.set_clip_box(pl.bbox)
        # ell.set_alpha(0.5)
        # ell.set_facecolor('none')
        pl.add_artist(ell) 
Example 11
Project: FlowKit   Author: whitews   File: _utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def calculate_ellipse(center_x, center_y, covariance_matrix, n_std_dev=3):
    values, vectors = np.linalg.eigh(covariance_matrix)
    order = values.argsort()[::-1]
    values = values[order]
    vectors = vectors[:, order]

    theta = np.degrees(np.arctan2(*vectors[:, 0][::-1]))

    # make all angles positive
    if theta < 0:
        theta += 360

    # Width and height are "full" widths, not radius
    width, height = 2.0 * n_std_dev * np.sqrt(values)

    ellipse = Ellipse(
        xy=(center_x, center_y),
        width=width,
        height=height,
        angle=float(theta)
    )

    return ellipse 
Example 12
Project: b2ac   Author: hbldh   File: ellipse.py    MIT License 5 votes vote down vote up
def __str__(self):
        return "Ellipse: Center = ({0:.2f}, {1:.2f}), Radii = ({2:.2f}, {3:.2f}), Angle = {4:.4f}".format(
            self.center_point[0], self.center_point[1], self.radii[0], self.radii[1], self.rotation_angle) 
Example 13
Project: Mastering-Machine-Learning-Algorithms   Author: PacktPublishing   File: generative_gaussian_mixtures.py    MIT License 5 votes vote down vote up
def show_dataset():
    fig, ax = plt.subplots(figsize=(20, 15))

    g1 = Ellipse(xy=m1, width=3 * np.sqrt(c1[0, 0]), height=3 * np.sqrt(c1[1, 1]), fill=False, linestyle='dashed',
                 linewidth=1)
    g1_1 = Ellipse(xy=m1, width=2 * np.sqrt(c1[0, 0]), height=2 * np.sqrt(c1[1, 1]), fill=False, linestyle='dashed',
                   linewidth=2)
    g1_2 = Ellipse(xy=m1, width=1.4 * np.sqrt(c1[0, 0]), height=1.4 * np.sqrt(c1[1, 1]), fill=False, linestyle='dashed',
                   linewidth=3)

    g2 = Ellipse(xy=m2, width=3 * np.sqrt(c2[0, 0]), height=3 * np.sqrt(c2[1, 1]), fill=False, linestyle='dashed',
                 linewidth=1)
    g2_1 = Ellipse(xy=m2, width=2 * np.sqrt(c2[0, 0]), height=2 * np.sqrt(c2[1, 1]), fill=False, linestyle='dashed',
                   linewidth=2)
    g2_2 = Ellipse(xy=m2, width=1.4 * np.sqrt(c2[0, 0]), height=1.4 * np.sqrt(c2[1, 1]), fill=False, linestyle='dashed',
                   linewidth=3)

    ax.scatter(X[Y == 0, 0], X[Y == 0, 1], color='#88d7f0', s=100)
    ax.scatter(X[Y == 1, 0], X[Y == 1, 1], color='#55ffec', s=100)
    ax.scatter(X[Y == -1, 0], X[Y == -1, 1], color='r', marker='d', s=25)

    ax.add_artist(g1)
    ax.add_artist(g1_1)
    ax.add_artist(g1_2)
    ax.add_artist(g2)
    ax.add_artist(g2_1)
    ax.add_artist(g2_2)

    ax.set_xlabel(r'$x_0$')
    ax.set_ylabel(r'$x_1$')
    ax.grid()

    plt.show() 
Example 14
Project: LaserTOF   Author: kyleuckert   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """Set the spine to be linear."""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 16
Project: straditize   Author: Chilipp   File: label_selection.py    GNU General Public License v3.0 5 votes vote down vote up
def highlight_small_selections(self, n=20):
        """Highlight labels that cover only a small portion of cells

        This method uses the :func:`skimage.morphology.remove_small_objects`
        to detect and highlight small features in the diagram. Each feature
        will be highlighted through an ellipsis around it.

        See Also
        --------
        remove_small_selection_ellipses"""
        from matplotlib.patches import Ellipse
        import skimage.morphology as skim
        if self._selection_arr is None:
            return
        arr = self.selected_part
        arr &= ~skim.remove_small_objects(arr, n)
        if not arr.any():
            return
        labeled, num_labels = skim.label(arr, 8, return_num=True)
        min_height = np.ceil(0.05 * arr.shape[0])
        min_width = np.ceil(0.05 * arr.shape[1])
        self._ellipses = artists = []
        extent = getattr(self, 'extent', None)
        if extent is not None:
            x0 = extent[0]
            y0 = min(extent[2:])
        else:
            x0 = y0 = 0
        for label in range(1, num_labels + 1):
            mask = labeled == label
            xmask = np.where(mask.any(axis=0))[0]
            width = xmask[-1] - xmask[0]
            xc = x0 + xmask[0] + width / 2. + 0.5
            ymask = np.where(mask.any(axis=1))[0]
            height = ymask[-1] - ymask[0]
            yc = y0 + ymask[0] + height / 2. + 0.5
            a = Ellipse((xc, yc), max(min_width, width + 2),
                        max(min_height, height + 2), edgecolor='b',
                        facecolor='b', alpha=0.3)
            artists.append(a)
            self._select_img.axes.add_patch(a) 
Example 17
Project: pybalu   Author: mbucchi   File: ellipses.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_ellipse(x, y, height, width, angle, axes):
    ell = Ellipse(xy=(x, y), height=height, width=width,
                  angle=angle, edgecolor="red", facecolor="none")
    axes.add_artist(ell)
    ell.set_clip_box(axes.bbox)
    return ell 
Example 18
Project: gmm_tutorial   Author: sitzikbs   File: visualization.py    MIT License 5 votes vote down vote up
def visualize_2D_gmm(points, w, mu, stdev, export=True):
    '''
    plots points and their corresponding gmm model in 2D
    Input: 
        points: N X 2, sampled points
        w: n_gaussians, gmm weights
        mu: 2 X n_gaussians, gmm means
        stdev: 2 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix)
    Output:
        None
    '''
    n_gaussians = mu.shape[1]
    N = int(np.round(points.shape[0] / n_gaussians))
    # Visualize data
    fig = plt.figure(figsize=(8, 8))
    axes = plt.gca()
    axes.set_xlim([-1, 1])
    axes.set_ylim([-1, 1])
    plt.set_cmap('Set1')
    colors = cmx.Set1(np.linspace(0, 1, n_gaussians))
    for i in range(n_gaussians):
        idx = range(i * N, (i + 1) * N)
        plt.scatter(points[idx, 0], points[idx, 1], alpha=0.3, c=colors[i])
        for j in range(8):
            axes.add_patch(
                patches.Ellipse(mu[:, i], width=(j+1) * stdev[0, i], height=(j+1) *  stdev[1, i], fill=False, color=[0.0, 0.0, 1.0, 1.0/(0.5*j+1)]))
        plt.title('GMM')
    plt.xlabel('X')
    plt.ylabel('Y')

    if export:
        if not os.path.exists('images/'): os.mkdir('images/')
        plt.savefig('images/2D_GMM_demonstration.png', dpi=100, format='png')

    plt.show() 
Example 19
Project: ble5-nrf52-mac   Author: tomasero   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 20
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 21
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_arc_angles():
    from matplotlib import patches
    # Ellipse parameters
    w = 2
    h = 1
    centre = (0.2, 0.5)
    scale = 2

    fig, axs = plt.subplots(3, 3)
    for i, ax in enumerate(axs.flat):
        theta2 = i * 360 / 9
        theta1 = theta2 - 45

        ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3))
        ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
        # Straight lines intersecting start and end of arc
        ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
                 centre[0],
                 scale * np.cos(np.deg2rad(theta2)) + centre[0]],
                [scale * np.sin(np.deg2rad(theta1)) + centre[1],
                 centre[1],
                 scale * np.sin(np.deg2rad(theta2)) + centre[1]])

        ax.set_xlim(-scale, scale)
        ax.set_ylim(-scale, scale)

        # This looks the same, but it triggers a different code path when it
        # gets large enough.
        w *= 10
        h *= 10
        centre = (centre[0] * 10, centre[1] * 10)
        scale *= 10 
Example 22
Project: ble5-nrf52-mac   Author: tomasero   File: test_artist.py    MIT License 5 votes vote down vote up
def test_patch_transform_of_none():
    # tests the behaviour of patches added to an Axes with various transform
    # specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # Draw an ellipse over data coord (2,2) by specifying device coords.
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # Not providing a transform of None puts the ellipse in data coordinates .
    e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)
    ax.add_patch(e)
    assert e._transform == ax.transData

    # Providing a transform of None puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         transform=None, alpha=0.5)
    assert e.is_transform_set() is True
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Providing an IdentityTransform puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=100, height=100,
                         transform=mtransforms.IdentityTransform(), alpha=0.5)
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Not providing a transform, and then subsequently "get_transform" should
    # not mean that "is_transform_set".
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         alpha=0.5)
    intermediate_transform = e.get_transform()
    assert e.is_transform_set() is False
    ax.add_patch(e)
    assert e.get_transform() != intermediate_transform
    assert e.is_transform_set() is True
    assert e._transform == ax.transData 
Example 23
Project: nanopores   Author: mitschabaude   File: plot_robustness.py    MIT License 5 votes vote down vote up
def make_legend_ellipse(legend, orig_handle, xdescent, ydescent,
    width, height, fontsize):
    return mpatches.Ellipse(xy=(0.5*width-0.5*xdescent, 0.5*height-0.5*ydescent),
        width = width+xdescent, height=(height+ydescent)) 
Example 24
Project: Computable   Author: ktraunmueller   File: spines.py    MIT License 5 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 25
Project: Computable   Author: ktraunmueller   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'

    # Behavior copied from mpatches.Ellipse: 
Example 26
Project: Computable   Author: ktraunmueller   File: anchored_artists.py    MIT License 5 votes vote down vote up
def __init__(self, transform, width, height, angle, loc,
                 pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs):
        """
        Draw an ellipse the size in data coordinate of the give axes.

        pad, borderpad in fraction of the legend font size (or prop)
        """
        self._box = AuxTransformBox(transform)
        self.ellipse = Ellipse((0,0), width, height, angle)
        self._box.add_artist(self.ellipse)

        AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon, **kwargs) 
Example 27
Project: prob_meteogram   Author: milankl   File: meteogram_alderaan.py    MIT License 5 votes vote down vote up
def clouds_plotter(axis,dates,highcloud,midcloud,lowcloud, interp=True):
    """ Adds the different types of clouds to a given axis."""
    # add sun (and moon?)
    for t in np.arange(len(dates)):
        idate = datetime.datetime(2018,6,7,12,0)
        while idate < dates[-1]:
            #sun = Circle((dates[t], 0.5), 0.2, color='yellow', zorder=0)
            sun = Ellipse((idate, 0.5), 0.4/2., 0.5, angle=0.0, color='yellow', zorder=0)
            axis.add_artist(sun)
            idate = idate + datetime.timedelta(1)

    # interpolate dates (if set)
    if interp:
        dates = spline_dates(dates)

    # add mean cloud covers and scale to [0...1]
    highcloudm = np.median(highcloud,axis=1)
    midcloudm = np.median(midcloud,axis=1)
    lowcloudm = np.median(lowcloud,axis=1)

    totalcloud=(highcloudm+midcloudm+lowcloudm)/3.
    totalcloudhalf=totalcloud/2.
    lowerbound=-totalcloudhalf+0.5
    upperbound=totalcloudhalf+0.5

    # don't plot clouds where totalcloud <= e.g. 0.05
    threshold=0.05

    # highcloud light grey, lowcloud dark grey
    axis.fill_between(dates, y1=lowerbound, y2=upperbound, color='0.95',zorder=1, alpha=0.8, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=upperbound-highcloudm/3., color='0.7',zorder=2, alpha=0.6, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=lowerbound+lowcloudm/3.,  color='0.4',zorder=3, alpha=0.3, edgecolor='none',where=totalcloud>=threshold)
    axis.set_facecolor('lightskyblue') 
Example 28
Project: prob_meteogram   Author: milankl   File: meteogram.py    MIT License 5 votes vote down vote up
def clouds_plotter(axis,dates,highcloud,midcloud,lowcloud, interp=True):
    """ Adds the different types of clouds to a given axis."""
    # add sun (and moon?)
    for t in np.arange(len(dates)):
        idate = datetime.datetime(2018,6,7,12,0)
        while idate < dates[-1]:
            #sun = Circle((dates[t], 0.5), 0.2, color='yellow', zorder=0)
            sun = Ellipse((idate, 0.5), 0.4/2., 0.5, angle=0.0, color='yellow', zorder=0)
            axis.add_artist(sun)
            idate = idate + datetime.timedelta(1)

    # interpolate dates (if set)
    if interp:
        dates = spline_dates(dates)

    # add mean cloud covers and scale to [0...1]
    highcloudm = np.median(highcloud,axis=1)
    midcloudm = np.median(midcloud,axis=1)
    lowcloudm = np.median(lowcloud,axis=1)

    totalcloud=(highcloudm+midcloudm+lowcloudm)/3.
    totalcloudhalf=totalcloud/2.
    lowerbound=-totalcloudhalf+0.5
    upperbound=totalcloudhalf+0.5

    # don't plot clouds where totalcloud <= e.g. 0.05
    threshold=0.05

    # highcloud light grey, lowcloud dark grey
    axis.fill_between(dates, y1=lowerbound, y2=upperbound, color='0.95',zorder=1, alpha=0.8, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=upperbound-highcloudm/3., color='0.7',zorder=2, alpha=0.6, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=lowerbound+lowcloudm/3.,  color='0.4',zorder=3, alpha=0.3, edgecolor='none',where=totalcloud>=threshold)
    axis.set_facecolor('lightskyblue') 
Example 29
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def clone_patch(patch):
    if isinstance(patch, mpatches.Rectangle):
        return mpatches.Rectangle(xy=patch.get_xy(),
                                  width=patch.get_width(),
                                  height=patch.get_height())
    if isinstance(patch, mpatches.Circle):
        return mpatches.Circle(xy=patch.get_xy(),
                               radius=patch.get_radius())
    if isinstance(patch, mpatches.Ellipse):
        return mpatches.Ellipse(xy=patch.get_xy(),
                                width=patch.get_width(),
                                height=patch.get_height())
    if isinstance(patch, mpatches.PathPatch):
        return mpatches.PathPatch(patch.get_path()) 
Example 30
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def patch_ellipse(node, trans, style, ids):
    if node.getAttribute("d") != "":
        return patch_path(node, trans, style, ids)
    return mpatches.Ellipse(xy=(float(node.getAttribute("cx")), float(node.getAttribute("cy"))),
                            width=float(node.getAttribute("rx"))*2,
                            height=float(node.getAttribute("ry"))*2,
                            transform=trans) 
Example 31
Project: neural-network-animation   Author: miloharper   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'

    # Behavior copied from mpatches.Ellipse: 
Example 32
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 33
Project: neural-network-animation   Author: miloharper   File: test_artist.py    MIT License 5 votes vote down vote up
def test_patch_transform_of_none():
    # tests the behaviour of patches added to an Axes with various transform
    # specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # Draw an ellipse over data coord (2,2) by specifying device coords.
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # Not providing a transform of None puts the ellipse in data coordinates .
    e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)
    ax.add_patch(e)
    assert e._transform == ax.transData

    # Providing a transform of None puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         transform=None, alpha=0.5)
    assert e.is_transform_set() is True
    ax.add_patch(e)
    assert isinstance(e._transform, mtrans.IdentityTransform)

    # Providing an IdentityTransform puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=100, height=100,
                         transform=mtrans.IdentityTransform(), alpha=0.5)
    ax.add_patch(e)
    assert isinstance(e._transform, mtrans.IdentityTransform)

    # Not providing a transform, and then subsequently "get_transform" should
    # not mean that "is_transform_set".
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         alpha=0.5)
    intermediate_transform = e.get_transform()
    assert e.is_transform_set() is False
    ax.add_patch(e)
    assert e.get_transform() != intermediate_transform
    assert e.is_transform_set() is True
    assert e._transform == ax.transData 
Example 34
Project: neural-network-animation   Author: miloharper   File: test_artist.py    MIT License 5 votes vote down vote up
def test_collection_transform_of_none():
    # tests the behaviour of collections added to an Axes with various
    # transform specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    #draw an ellipse over data coord (2,2) by specifying device coords
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # not providing a transform of None puts the ellipse in data coordinates
    e = mpatches.Ellipse(xy_data, width=1, height=1)
    c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5)
    ax.add_collection(c)
    # the collection should be in data coordinates
    assert c.get_offset_transform() + c.get_transform() == ax.transData

    # providing a transform of None puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=120, height=120)
    c = mcollections.PatchCollection([e], facecolor='coral',
                                     alpha=0.5)
    c.set_transform(None)
    ax.add_collection(c)
    assert isinstance(c.get_transform(), mtrans.IdentityTransform)

    # providing an IdentityTransform puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=100, height=100)
    c = mcollections.PatchCollection([e], transform=mtrans.IdentityTransform(),
                                     alpha=0.5)
    ax.add_collection(c)
    assert isinstance(c._transOffset, mtrans.IdentityTransform) 
Example 35
Project: eaglemine   Author: wenchieh   File: ploter_aux.py    MIT License 5 votes vote down vote up
def _construct_ellipses_(clusters_para, scale=5.0, SINGLE_PARAS=5):
    N_m = len(clusters_para)

    ell, mus = list(), list()
    left, right, bottom, up = 0, 0, 0, 0
    for k in range(N_m):
        norm = 1.0
        para = clusters_para[k]
        mu = para[:2][::-1]
        cov = np.array([[para[2], para[3]],[para[3], para[4]]])

        angle = _covmat_angle_(cov)
        w, h = scale * np.sqrt(cov[0, 0]) / norm, scale * np.sqrt(cov[1, 1]) / norm
        if w + mu[0] > right:
            right = w + mu[0]
        if h + mu[1] > up:
            up = h + mu[1]
        if -h + mu[1] < bottom:
            bottom = -h + mu[1]

        if mu[1] < 0:    # for  better illustration
            w *= 1.5
            h *= 1.5

        mus.append(mu)
        ell.append(Ellipse(mu, w, h, angle))

    return ell, mus, [left, right, bottom, up]

## ellipses labeled heatmap plot 
Example 36
Project: pyMHT   Author: erikliland   File: pyTarget.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plotCovarianceEllipse(self, eta2):
        from matplotlib.patches import Ellipse
        lambda_, _ = np.linalg.eig(self.kalmanFilter.S)
        ell = Ellipse(xy=(self.kalmanFilter.x_bar[0], self.kalmanFilter.x_bar[1]),
                      width=np.sqrt(lambda_[0]) * np.sqrt(eta2) * 2,
                      height=np.sqrt(lambda_[1]) * np.sqrt(eta2) * 2,
                      angle=np.rad2deg(np.arctan2(lambda_[1], lambda_[0])),
                      linewidth=2,
                      )
        ell.set_facecolor('none')
        ell.set_linestyle("dotted")
        ell.set_alpha(0.5)
        ax = plt.subplot(111)
        ax.add_artist(ell) 
Example 37
Project: GraphicDesignPatternByPython   Author: Relph1119   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 38
Project: python3_ios   Author: holzschu   File: anchored_artists.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, transform, width, height, angle, loc,
                 pad=0.1, borderpad=0.1, prop=None, frameon=True):
        """
        Draw an ellipse the size in data coordinate of the give axes.

        pad, borderpad in fraction of the legend font size (or prop)
        """
        self._box = AuxTransformBox(transform)
        self.ellipse = Ellipse((0, 0), width, height, angle)
        self._box.add_artist(self.ellipse)
        super().__init__(loc, pad=pad, borderpad=borderpad,
                         child=self._box, prop=prop, frameon=frameon) 
Example 39
Project: python3_ios   Author: holzschu   File: legend_guide.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
        p = mpatches.Ellipse(xy=center, width=width + xdescent,
                             height=height + ydescent)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p] 
Example 40
Project: python3_ios   Author: holzschu   File: spines.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 41
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 42
Project: python3_ios   Author: holzschu   File: test_artist.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_patch_transform_of_none():
    # tests the behaviour of patches added to an Axes with various transform
    # specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # Draw an ellipse over data coord (2,2) by specifying device coords.
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # Not providing a transform of None puts the ellipse in data coordinates .
    e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)
    ax.add_patch(e)
    assert e._transform == ax.transData

    # Providing a transform of None puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         transform=None, alpha=0.5)
    assert e.is_transform_set() is True
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Providing an IdentityTransform puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=100, height=100,
                         transform=mtransforms.IdentityTransform(), alpha=0.5)
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Not providing a transform, and then subsequently "get_transform" should
    # not mean that "is_transform_set".
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         alpha=0.5)
    intermediate_transform = e.get_transform()
    assert e.is_transform_set() is False
    ax.add_patch(e)
    assert e.get_transform() != intermediate_transform
    assert e.is_transform_set() is True
    assert e._transform == ax.transData 
Example 43
Project: python3_ios   Author: holzschu   File: test_artist.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_collection_transform_of_none():
    # tests the behaviour of collections added to an Axes with various
    # transform specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # draw an ellipse over data coord (2,2) by specifying device coords
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # not providing a transform of None puts the ellipse in data coordinates
    e = mpatches.Ellipse(xy_data, width=1, height=1)
    c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5)
    ax.add_collection(c)
    # the collection should be in data coordinates
    assert c.get_offset_transform() + c.get_transform() == ax.transData

    # providing a transform of None puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=120, height=120)
    c = mcollections.PatchCollection([e], facecolor='coral',
                                     alpha=0.5)
    c.set_transform(None)
    ax.add_collection(c)
    assert isinstance(c.get_transform(), mtransforms.IdentityTransform)

    # providing an IdentityTransform puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=100, height=100)
    c = mcollections.PatchCollection([e],
                                 transform=mtransforms.IdentityTransform(),
                                 alpha=0.5)
    ax.add_collection(c)
    assert isinstance(c._transOffset, mtransforms.IdentityTransform) 
Example 44
Project: Machine-Learning-Algorithms   Author: rishab-pdx   File: gaussianMM.py    MIT License 5 votes vote down vote up
def plotGaussian(self, data, **kwargs):
        clusters = self.clusters
        colors = iter(cm.gist_rainbow(numpy.linspace(0, 1, len(clusters))))
        centroids = self.centroids
        assignments = self.assignments
        covs = self.covs
        plt.subplot(121)
        ax = plt.gca()
        plt.xlabel('X1')
        plt.ylabel('X2')
        plt.title('Gaussian Mixture Model With K = '+str(clusters.shape[0]))
        for c in range(clusters.shape[0]):
            color = next(colors)
            eigvals, eigvecs = lg.eigh(covs[c])
            eigvals = 3. * numpy.sqrt(2.) * numpy.sqrt(eigvals)
            u = eigvecs[0]/lg.norm(eigvecs[0])
            angle = numpy.arctan(u[1]/u[0])
            angle = 180. * angle/numpy.pi
            ellipse = Ellipse(xy=centroids[c], width=eigvals[0],
                              height=eigvals[1], angle=180.+angle, color=color, linewidth=0.5, alpha=0.5, **kwargs)
            ax.add_artist(ellipse)
            plt.scatter(data[assignments == c, 0],
                        data[assignments == c, 1], color=color, s=10, marker="o")
        # end
        for c in range(centroids.shape[0]):
            plt.scatter(centroids[c][0], centroids[c]
                        [1], color="k", s=50, marker="*")
        plt.subplot(122)
        plt.xlabel('Iterations')
        plt.ylabel('Negative Log likelihood')
        plt.title("Loglikeihood vs Number Of Iterations")
        plt.plot(self.likelihoods[1:])
        plt.show() 
Example 45
Project: demos   Author: jnez71   File: resection_ekf.py    MIT License 5 votes vote down vote up
def callback(iter):
    global ellipse, estim_point, estim_head
    ellipse.remove()
    estim_point.remove()
    estim_head.remove()
    evals, evecs = npl.eigh(posterior_covar[:2, :2])
    ellipse = Ellipse(xy=prior_mean, width=conf*np.sqrt(evals[-1]), height=conf*np.sqrt(evals[0]),
                      angle=np.rad2deg(np.arctan2(evecs[1, -1], evecs[0, -1])),
                      edgecolor='r', lw=1, facecolor='none')
    ax.add_artist(ellipse)
    estim_point = ax.scatter(prior_mean[0], prior_mean[1], c='r', label="estimate")
    estim_head = ax.quiver(prior_mean[0], prior_mean[1], np.cos(prior_mean[2]), np.sin(prior_mean[2]), color='r', scale=20, width=5e-3)
    update()
    return [] 
Example 46
Project: demos   Author: jnez71   File: mc_vs_lin.py    MIT License 5 votes vote down vote up
def plot_covar(ax, covar, mean, conf=2*np.sqrt(6), edgecolor='k', linewidth=2, label=""):
    eigvals, eigvecs = np.linalg.eigh(covar)
    ellipse = Ellipse(xy=mean, width=conf*np.sqrt(eigvals[-1]), height=conf*np.sqrt(eigvals[0]),
                      angle=np.rad2deg(np.arctan2(eigvecs[1, -1], eigvecs[0, -1])),
                      facecolor='none', edgecolor=edgecolor, linewidth=linewidth, label=label)
    ax.add_artist(ellipse)

# Visualize 
Example 47
Project: vi_vae_gmm   Author: wangg12   File: vi_GMM_2d.py    Apache License 2.0 5 votes vote down vote up
def get_plot_buf(x, clusters, mu, logstd, true_mu, true_logstd):
    N = x.shape[0]
    K = mu.shape[0]
    fig = plt.figure()
    # print(clusters.shape)
    # print(x.shape)
    ax = fig.add_subplot(111, aspect='auto')
    plt.scatter(x[:, 0], x[:, 1], c=clusters, s=50)
    # print(mu, logstd)
    ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]),
                angle=0, facecolor='none', zorder=10, edgecolor='g', label='predict' if i==0 else None)
            for i, (mean_, logstd_) in enumerate(zip(mu, logstd))]
    true_ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]),
                angle=0, facecolor='none', zorder=10, edgecolor='r', label='true' if i==0 else None)
            for i,(mean_, logstd_) in enumerate(zip(true_mu, true_logstd))]
    # print(ells[0])
    [ax.add_patch(ell) for ell in ells]
    [ax.add_patch(true_ell) for true_ell in true_ells]
    ax.legend(loc='best')
    ax.set_title('N={},K={}'.format(N, K))
    plt.autoscale(True)
    buf = io.BytesIO()
    fig.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    return buf 
Example 48
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 49
Project: linear_neuron   Author: uglyboxer   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'

    # Behavior copied from mpatches.Ellipse: 
Example 50
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 51
Project: influenza-reassortment-analysis   Author: ericmjl   File: circos.py    MIT License 5 votes vote down vote up
def add_nodes(self):
		r = self.radius
		node_r = self.node_radius
		for node in self.nodes:
			theta = self.node_theta(node)
			x, y = get_cartesian(r, theta)
			node_patch = patches.Ellipse((x,y), node_r, node_r, facecolor=self.nodecolor, lw=0)
			self.ax.add_patch(node_patch) 
Example 52
Project: BP-AR-HMM   Author: mathDR   File: plotter.py    MIT License 5 votes vote down vote up
def generate_emissions(theta,data):
  def _eigsorted(cov):
    vals,vecs = np.linalg.eigh(cov)
    order = vals.argsort()[::-1]
    return vals[order],vecs[:,order]
  xmin = np.inf; xmax = -np.inf
  ymin = np.inf; ymax = -np.inf
  fig = plt.figure()
  ax = fig.add_subplot(111)
  for i in range(len(data)):
    ax.plot(data[i][:,0],data[i][:,1],'k.')
    xmin = np.min([xmin,np.min(data[i][:,0])])
    xmax = np.max([xmax,np.max(data[i][:,0])])
    ymin = np.min([ymin,np.min(data[i][:,1])])
    ymax = np.max([ymax,np.max(data[i][:,1])])

  vol = [0.25,0.5,0.75,0.95, 0.99]

  ell = []
  for i in range(len(theta)):
    pos = theta[i].mean
    vals,vecs = _eigsorted(theta[i].var)
    th = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    for v in vol:
      width,height = 2.0*np.sqrt(chi2.ppf(v,2))*np.sqrt(vals)
      ell.append(Ellipse(xy=pos,width=width,height=height,angle=th))
  for i,e in enumerate(ell):
    ax.add_artist(e)
    e.set_facecolor(my_color_map(i))
    e.set_alpha(0.5)

  ax.set_xlim(xmin, xmax)
  ax.set_ylim(ymin, ymax)
  plt.show() 
Example 53
Project: psychrometric-chart-makeover   Author: buds-lab   File: spines.py    MIT License 5 votes vote down vote up
def set_patch_line(self):
        """set the spine to be linear"""
        self._patch_type = 'line'
        self.stale = True

    # Behavior copied from mpatches.Ellipse: 
Example 54
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a cartesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 55
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_arc_angles():
    from matplotlib import patches
    # Ellipse parameters
    w = 2
    h = 1
    centre = (0.2, 0.5)
    scale = 2

    fig, axs = plt.subplots(3, 3)
    for i, ax in enumerate(axs.flat):
        theta2 = i * 360 / 9
        theta1 = theta2 - 45

        ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3))
        ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
        # Straight lines intersecting start and end of arc
        ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
                 centre[0],
                 scale * np.cos(np.deg2rad(theta2)) + centre[0]],
                [scale * np.sin(np.deg2rad(theta1)) + centre[1],
                 centre[1],
                 scale * np.sin(np.deg2rad(theta2)) + centre[1]])

        ax.set_xlim(-scale, scale)
        ax.set_ylim(-scale, scale)

        # This looks the same, but it triggers a different code path when it
        # gets large enough.
        w *= 10
        h *= 10
        centre = (centre[0] * 10, centre[1] * 10)
        scale *= 10 
Example 56
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_artist.py    MIT License 5 votes vote down vote up
def test_patch_transform_of_none():
    # tests the behaviour of patches added to an Axes with various transform
    # specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # Draw an ellipse over data coord (2,2) by specifying device coords.
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # Not providing a transform of None puts the ellipse in data coordinates .
    e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)
    ax.add_patch(e)
    assert e._transform == ax.transData

    # Providing a transform of None puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         transform=None, alpha=0.5)
    assert e.is_transform_set()
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Providing an IdentityTransform puts the ellipse in device coordinates.
    e = mpatches.Ellipse(xy_pix, width=100, height=100,
                         transform=mtransforms.IdentityTransform(), alpha=0.5)
    ax.add_patch(e)
    assert isinstance(e._transform, mtransforms.IdentityTransform)

    # Not providing a transform, and then subsequently "get_transform" should
    # not mean that "is_transform_set".
    e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
                         alpha=0.5)
    intermediate_transform = e.get_transform()
    assert not e.is_transform_set()
    ax.add_patch(e)
    assert e.get_transform() != intermediate_transform
    assert e.is_transform_set()
    assert e._transform == ax.transData 
Example 57
Project: nstar-plot   Author: awsteiner   File: nstar_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def base_star(self):
        # Base star
        N=100
        ang=0
        for i in range(0,N):
            centx=0.5-float(i)*0.14/N
            centy=0.5+float(i)*0.14/N
            size1=0.6-float(i)*0.56/N
            size2=0.6-float(i)*0.56/N
            green=float(i)/N
            base=Ellipse((centx,centy),size1,size2,lw=0,angle=ang)
            base.set_facecolor((1,green,0))
            self.ax.add_artist(base) 
Example 58
Project: bayesianpy   Author: morganics   File: iris_clustering_visualisation.py    Apache License 2.0 5 votes vote down vote up
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the
    ellipse patch artist.

    Parameters
    ----------
        cov : The 2x2 covariance matrix to base the ellipse on
        pos : The location of the center of the ellipse. Expects a 2-element
            sequence of [x0, y0].
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    if ax is None:
        ax = plt.gca()

    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))

    # Width and height are "full" widths, not radius
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)

    ax.add_artist(ellip)
    return ellip 
Example 59
Project: bayesianpy   Author: morganics   File: visual.py    Apache License 2.0 5 votes vote down vote up
def _plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
        """
        Plots an `nstd` sigma error ellipse based on the specified covariance
        matrix (`cov`). Additional keyword arguments are passed on to the
        ellipse patch artist.

        Parameters
        ----------
            cov : The 2x2 covariance matrix to base the ellipse on
            pos : The location of the center of the ellipse. Expects a 2-element
                sequence of [x0, y0].
            nstd : The radius of the ellipse in numbers of standard deviations.
                Defaults to 2 standard deviations.
            ax : The axis that the ellipse will be plotted on. Defaults to the
                current axis.
            Additional keyword arguments are pass on to the ellipse patch.

        Returns
        -------
            A matplotlib ellipse artist
        """
        from matplotlib import pyplot as plt
        from matplotlib.patches import Ellipse

        def eigsorted(cov):
            vals, vecs = np.linalg.eigh(cov)
            order = vals.argsort()[::-1]
            return vals[order], vecs[:, order]

        if ax is None:
            ax = plt.gca()

        vals, vecs = eigsorted(cov)
        theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))

        # Width and height are "full" widths, not radius
        width, height = 2 * nstd * np.sqrt(vals)
        ellip = Ellipse(xy=pos, width=width, height=height, angle=theta,
                        **kwargs)
        ax.add_artist(ellip)
        return ellip 
Example 60
Project: pyplis   Author: jgliss   File: doascalib.py    GNU General Public License v3.0 4 votes vote down vote up
def plot(self, ax=None):
        """Draw the current FOV position into the current correlation img."""
        if ax is None:
            fig, ax = subplots(1, 1, figsize=(12, 8))
        else:
            fig = ax.figure
        img = self.corr_img.img
        vmin, vmax = img.min(), img.max()
        cmap = shifted_color_map(vmin, vmax, cmap=RdBu)
        h, w = img.shape
        disp = ax.imshow(img, vmin=vmin, vmax=vmax, cmap=cmap)
        cb = fig.colorbar(disp, ax=ax, shrink=0.9)
        cx, cy = self.pixel_position_center(1)
        if self.method == "ifr":
            popt = self.popt
            cb.set_label(r"FOV fraction [$10^{-2}$ pixel$^{-1}$]")

            xgrid, ygrid = mesh_from_img(img)
            if len(popt) == 7:
                ell = Ellipse(xy=(popt[1], popt[2]), width=popt[3],
                              height=popt[3] / popt[4], color="k", lw=2,
                              fc="lime", alpha=.5)
            else:
                ell = Ellipse(xy=(popt[1], popt[2]), width=popt[3],
                              height=popt[3] / popt[4], angle=popt[7],
                              color="k", lw=2, fc="lime", alpha=.5)

            ax.add_artist(ell)
            ax.axhline(self.cy_rel, ls="--", color="k")
            ax.axvline(self.cx_rel, ls="--", color="k")

            ax.get_xaxis().set_ticks([0, self.cx_rel, w])
            ax.get_yaxis().set_ticks([0, self.cy_rel, h])

            # ax.set_axis_off()
            ax.set_title(r"Corr img (IFR), pos abs (x,y): (%d, %d), "
                         "lambda=%.1e"
                         % (cx, cy, self.search_settings["ifrlbda"]))

        elif self.method == "pearson":
            cb.set_label(r"Pearson corr. coeff.")
            ax.autoscale(False)

            c = Circle((self.cx_rel, self.cy_rel), self.radius_rel, ec="k",
                       lw=2, fc="lime", alpha=.5)
            ax.add_artist(c)
            ax.set_title("Corr img (pearson), pos abs (x,y): (%d, %d)"
                         % (cx, cy))
            ax.get_xaxis().set_ticks([0, self.cx_rel, w])
            ax.get_yaxis().set_ticks([0, self.cy_rel, h])
            ax.axhline(self.cy_rel, ls="--", color="k")
            ax.axvline(self.cx_rel, ls="--", color="k")
        ax.set_xlabel("Pixel row")
        ax.set_ylabel("Pixel column")
        return ax 
Example 61
Project: LaserTOF   Author: kyleuckert   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            msg = "'path' must be an instance of 'matplotlib.path.Path'"
            raise ValueError(msg)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 62
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 63
Project: ble5-nrf52-mac   Author: tomasero   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 64
Project: pylustrator   Author: rgerum   File: snap.py    GNU General Public License v3.0 4 votes vote down vote up
def get_positions(self):
        points = []
        if isinstance(self.target, Rectangle):
            points.append(self.target.get_xy())
            p2 = (self.target.get_x() + self.target.get_width(), self.target.get_y() + self.target.get_height())
            points.append(p2)
        elif isinstance(self.target, Ellipse):
            c = self.target.center
            w = self.target.width
            h = self.target.height
            points.append((c[0]-w/2, c[1]-h/2))
            points.append((c[0]+w/2, c[1]+h/2))
        elif isinstance(self.target, FancyArrowPatch):
            points.append(self.target._posA_posB[0])
            points.append(self.target._posA_posB[1])
            points.extend(self.target.get_path().vertices)
        elif isinstance(self.target, Text):
            points.append(self.target.get_position())
            if checkXLabel(self.target):
                points[0] = (points[0][0], self.label_y)
            elif checkYLabel(self.target):
                points[0] = (self.label_x, points[0][1])
            if getattr(self.target, "xy", None) is not None:
                points.append(self.target.xy)
            bbox = self.target.get_bbox_patch()
            if bbox:
                points.append(bbox.get_transform().transform((bbox.get_x(), bbox.get_y())))
                points.append(bbox.get_transform().transform((bbox.get_x()+bbox.get_width(), bbox.get_y()+bbox.get_height())))
            points[-2:] = self.transform_inverted_points(points[-2:])
        elif isinstance(self.target, Axes):
            p1, p2 = np.array(self.target.get_position())
            points.append(p1)
            points.append(p2)
        elif isinstance(self.target, Legend):
            bbox = self.target.get_frame().get_bbox()
            if isinstance(self.target._get_loc(), int):
                # if the legend doesn't have a location yet, use the left bottom corner of the bounding box
                self.target._set_loc(tuple(self.target.axes.transAxes.inverted().transform(tuple([bbox.x0, bbox.y0]))))
            points.append(self.target.axes.transAxes.transform(self.target._get_loc()))
            # add points to span bounding box around the frame
            points.append([bbox.x0, bbox.y0])
            points.append([bbox.x1, bbox.y1])
        return self.transform_points(points) 
Example 65
Project: pylustrator   Author: rgerum   File: snap.py    GNU General Public License v3.0 4 votes vote down vote up
def set_positions(self, points):
        points = self.transform_inverted_points(points)

        if isinstance(self.target, Rectangle):
            self.target.set_xy(points[0])
            self.target.set_width(points[1][0] - points[0][0])
            self.target.set_height(points[1][1] - points[0][1])
            if self.target.get_label() is None or not self.target.get_label().startswith("_rect"):
                self.figure.change_tracker.addChange(self.target, ".set_xy([%f, %f])" % tuple(self.target.get_xy()))
                self.figure.change_tracker.addChange(self.target, ".set_width(%f)" % self.target.get_width())
                self.figure.change_tracker.addChange(self.target, ".set_height(%f)" % self.target.get_height())
        elif isinstance(self.target, Ellipse):
            self.target.center = np.mean(points, axis=0)
            self.target.width = points[1][0] - points[0][0]
            self.target.height = points[1][1] - points[0][1]
            self.figure.change_tracker.addChange(self.target, ".center = (%f, %f)" % tuple(self.target.center))
            self.figure.change_tracker.addChange(self.target, ".width = %f" % self.target.width)
            self.figure.change_tracker.addChange(self.target, ".height = %f" % self.target.height)
        elif isinstance(self.target, FancyArrowPatch):
            self.target.set_positions(points[0], points[1])
            self.figure.change_tracker.addChange(self.target, ".set_positions(%s, %s)" % (tuple(points[0]), tuple(points[1])))
        elif isinstance(self.target, Text):
            if checkXLabel(self.target):
                axes = checkXLabel(self.target)
                axes.xaxis.labelpad = -(points[0][1]-self.target.pad_offset)/self.label_factor
                self.figure.change_tracker.addChange(axes,
                                                     ".xaxis.labelpad = %f" % axes.xaxis.labelpad)

                self.target.set_position(points[0])
                self.label_y = points[0][1]
            elif checkYLabel(self.target):
                axes = checkYLabel(self.target)
                axes.yaxis.labelpad = -(points[0][0]-self.target.pad_offset)/self.label_factor
                self.figure.change_tracker.addChange(axes,
                                                     ".yaxis.labelpad = %f" % axes.yaxis.labelpad)

                self.target.set_position(points[0])
                self.label_x = points[0][0]
            else:
                self.target.set_position(points[0])
                self.figure.change_tracker.addChange(self.target, ".set_position([%f, %f])" % self.target.get_position())
                if getattr(self.target, "xy", None) is not None:
                    self.target.xy = points[1]
                    self.figure.change_tracker.addChange(self.target, ".xy = (%f, %f)" % tuple(self.target.xy))
        elif isinstance(self.target, Legend):
            point = self.target.axes.transAxes.inverted().transform(self.transform_inverted_points(points)[0])
            self.target._loc = tuple(point)
            self.figure.change_tracker.addChange(self.target, "._set_loc((%f, %f))" % tuple(point))
        elif isinstance(self.target, Axes):
            position = np.array([points[0], points[1]-points[0]]).flatten()
            if self.fixed_aspect:
                position[3] = position[2]*self.target.get_position().height/self.target.get_position().width
            self.target.set_position(position)
            self.figure.change_tracker.addChange(self.target, ".set_position([%f, %f, %f, %f])" % tuple(np.array([points[0], points[1]-points[0]]).flatten())) 
Example 66
Project: neural-network-animation   Author: miloharper   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 67
Project: Mastering-Machine-Learning-Algorithms-Second-Edition   Author: PacktPublishing   File: generative_gaussian_mixtures.py    MIT License 4 votes vote down vote up
def show_dataset():
    w1, v1 = np.linalg.eigh(c1)
    w2, v2 = np.linalg.eigh(c2)

    nv1 = v1 / np.linalg.norm(v1)
    nv2 = v2 / np.linalg.norm(v2)

    a1 = np.arccos(np.dot(nv1[:, 1], [1.0, 0.0]) / np.linalg.norm(nv1[:, 1])) * 180.0 / np.pi
    a2 = np.arccos(np.dot(nv2[:, 1], [1.0, 0.0]) / np.linalg.norm(nv2[:, 1])) * 180.0 / np.pi

    fig, ax = plt.subplots(figsize=(20, 15))

    ax.scatter(X[Y == 0, 0], X[Y == 0, 1], s=120, marker='o', label='Class 1')
    ax.scatter(X[Y == 1, 0], X[Y == 1, 1], s=120, marker='d', label='Class 2')
    ax.scatter(X[Y == -1, 0], X[Y == -1, 1], s=120, marker='x', label='Unlabeled')

    g1 = Ellipse(xy=m1, width=w1[1] * 3, height=w1[0] * 3, fill=False, linestyle='dashed', angle=a1, color='black',
                 linewidth=1)
    g1_1 = Ellipse(xy=m1, width=w1[1] * 2, height=w1[0] * 2, fill=False, linestyle='dashed', angle=a1, color='black',
                   linewidth=2)
    g1_2 = Ellipse(xy=m1, width=w1[1] * 1.4, height=w1[0] * 1.4, fill=False, linestyle='dashed', angle=a1,
                   color='black', linewidth=3)

    g2 = Ellipse(xy=m2, width=w2[1] * 3, height=w2[0] * 3, fill=False, linestyle='dashed', angle=a2, color='black',
                 linewidth=1)
    g2_1 = Ellipse(xy=m2, width=w2[1] * 2, height=w2[0] * 2, fill=False, linestyle='dashed', angle=a2, color='black',
                   linewidth=2)
    g2_2 = Ellipse(xy=m2, width=w2[1] * 1.4, height=w2[0] * 1.4, fill=False, linestyle='dashed', angle=a2,
                   color='black', linewidth=3)

    ax.set_xlabel(r'$x_0$', fontsize=18)
    ax.set_ylabel(r'$x_1$', fontsize=18)

    ax.add_artist(g1)
    ax.add_artist(g1_1)
    ax.add_artist(g1_2)
    ax.add_artist(g2)
    ax.add_artist(g2_1)
    ax.add_artist(g2_2)

    ax.legend(fontsize=18)

    plt.show() 
Example 68
Project: GraphicDesignPatternByPython   Author: Relph1119   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 69
Project: python3_ios   Author: holzschu   File: spines.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 70
Project: prepub   Author: OmnesRes   File: views.py    MIT License 4 votes vote down vote up
def make_plot(request):
    if 'size' in request.META['HTTP_REFERER'] and 'mean' in request.META['HTTP_REFERER']:
        from data import *
        from matplotlib.backends.backend_agg import FigureCanvasAgg
        from matplotlib.figure import Figure
        import matplotlib.pyplot as plt
        from matplotlib.patches import Ellipse
        import gc
        import numpy as np
        decimal=int(request.META['HTTP_REFERER'].split('mean=')[1].split('&')[0].split('.')[1])
        size=int(request.META['HTTP_REFERER'].split('size=')[1].strip())
        fig=Figure(figsize=(22.62372, 12),facecolor='white')
        fig.subplots_adjust(bottom=0.15)
        fig.subplots_adjust(left=0.06)
        fig.subplots_adjust(right=.99)
        fig.subplots_adjust(top=.99)
        ax=fig.add_subplot(111,)
        white_green = make_colormap({0:'#66ff66',1:'red'})
        Z=np.rot90(np.array(eval(final_data)),k=1)
        Z=Z[::-1]
        ax.pcolor(Z,cmap=white_green)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.set_xticks([i+.5 for i in range(100)])
        ax.set_xticklabels([str(i) for i in range(1,101)],rotation=270)
        ax.set_yticks([i-.5 for i in range(100)][::-1][::2])
        ax.set_yticklabels(["%02d" % i for i in range(-1,99)][::-1][::2])
        ax.set_ylabel('Decimal Value',fontsize=40,labelpad=10)
        ax.set_xlabel('Sample Size',fontsize=40,labelpad=0)
        ax.tick_params(axis='x',length=15,width=2,direction='out',labelsize=12,pad=15)
        ax.tick_params(axis='y',length=15,width=3,direction='out',labelsize=16,pad=20)
        circle1=Ellipse((size-.5,decimal+.5),width=1.06,height=2,color='k',fill=False,lw=4,clip_on=False)
        fig.gca().add_artist(circle1)
        canvas=FigureCanvasAgg(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)
        fig.clf()
        plt.close(fig)
        del canvas
        gc.collect()
        return response 
Example 71
Project: hrvanalysis   Author: Aura-healthcare   File: plot.py    GNU General Public License v3.0 4 votes vote down vote up
def plot_poincare(nn_intervals: List[float], plot_sd_features: bool = True):
    """
    Pointcare / Lorentz Plot of the NN Intervals

    Arguments
    ---------
    nn_intervals : list
        list of NN intervals
    plot_sd_features : bool
        Option to show or not SD1 and SD2 features on plot. By default, set to True.

    Notes
    ---------
    The transverse axis (T) reflects beat-to-beat variation
    the longitudinal axis (L) reflects the overall fluctuation
    """
    # For Lorentz / poincaré Plot
    ax1 = nn_intervals[:-1]
    ax2 = nn_intervals[1:]

    # compute features for ellipse's height, width and center
    dict_sd1_sd2 = get_poincare_plot_features(nn_intervals)
    sd1 = dict_sd1_sd2["sd1"]
    sd2 = dict_sd1_sd2["sd2"]
    mean_nni = np.mean(nn_intervals)

    # Plot options and settings
    style.use("seaborn-darkgrid")
    fig = plt.figure(figsize=(12, 12))
    ax = fig.add_subplot(111)
    plt.title("Poincaré / Lorentz Plot", fontsize=20)
    plt.xlabel('NN_n (s)', fontsize=15)
    plt.ylabel('NN_n+1 (s)', fontsize=15)
    plt.xlim(min(nn_intervals) - 10, max(nn_intervals) + 10)
    plt.ylim(min(nn_intervals) - 10, max(nn_intervals) + 10)

    # Poincaré Plot
    ax.scatter(ax1, ax2, c='b', s=2)

    if plot_sd_features:
        # Ellipse plot settings
        ells = Ellipse(xy=(mean_nni, mean_nni), width=2 * sd2 + 1,
                       height=2 * sd1 + 1, angle=45, linewidth=2,
                       fill=False)
        ax.add_patch(ells)

        ells = Ellipse(xy=(mean_nni, mean_nni), width=2 * sd2,
                       height=2 * sd1, angle=45)
        ells.set_alpha(0.05)
        ells.set_facecolor("blue")
        ax.add_patch(ells)

        # Arrow plot settings
        sd1_arrow = ax.arrow(mean_nni, mean_nni, -sd1 * np.sqrt(2) / 2, sd1 * np.sqrt(2) / 2,
                             linewidth=3, ec='r', fc="r", label="SD1")
        sd2_arrow = ax.arrow(mean_nni, mean_nni, sd2 * np.sqrt(2) / 2, sd2 * np.sqrt(2) / 2,
                             linewidth=3, ec='g', fc="g", label="SD2")

        plt.legend(handles=[sd1_arrow, sd2_arrow], fontsize=12, loc="best")
    plt.show() 
Example 72
Project: mlcv-tutorial   Author: johny-c   File: clustering.py    GNU General Public License v3.0 4 votes vote down vote up
def draw_ellipses_iteration(ax, data, covs, title='', colors='b', marker='o',
                            ellipses_to_remove=None, pause_time=0.3):
    """Draw ellipses as estimated in a single iteration of an algorithm.

    Parameters
    ----------
    ax : matplotlib.axes.Axes instance
        The axes to draw in.

    data : array, shape (n_components, n_features)
        The data to scatter plot.

    covs : array, shape (n_components, n_features, n_features)
        The covariance matrices of the components

    title : str (optional)
        Title of the plot.

    colors : array, shape (n_samples, 4) or str (optional)
        RGBA color per sample or single string

    marker : str, (optional)
        The representation of the points.

    pause_time : float (optional)
        How long to wait so the drawing can be rendered and observed.

    ellipses_to_remove : list
        List of ellipses from previous iteration(s) to be cleared.

    Returns
    -------
    ellipses : list[matplotlib.patches.Ellipse]
        The drawn ellipses objects.

    """

    if ellipses_to_remove is not None:
        [e.remove() for e in ellipses_to_remove]

    ellipses = []
    plt.sca(ax)
    plt.scatter(data[:, 0], data[:, 1], c=colors, marker=marker, lw=0, s=50)
    n_components, n_features = data.shape
    for k in range(n_components):
        ellipse = draw_ellipse(ax, data[k, :], covs[k, :, :])
        ellipses.append(ellipse)

    plt.title('{}'.format(title), fontweight='bold')
    plt.draw()
    plt.pause(pause_time)
    return ellipses


########################################################################### 
Example 73
Project: mlcv-tutorial   Author: johny-c   File: clustering.py    GNU General Public License v3.0 4 votes vote down vote up
def draw_ellipse(ax, center, cov, facecolor='lightblue', edgecolor='r'):
    """

    Parameters
    ----------
    ax : matplotlib.axes.Axes instance
        The axes to draw in.

    center : array-like, shape (2,)
        Center coordinates of the ellipse.

    cov : array, shape (n_features, n_features)
        Covariance matrix associated with this ellipse.

    facecolor : array, shape (n_components, 4) or str (optional)
        Face color of the ellipse.

    edgecolor : str (optional)
        Perimeter color of the eliipse

    Returns
    -------
    ellipse : matplotlib.patches.Ellipse
        The drawn ellipse object.

    """
    v, w = np.linalg.eigh(cov)
    u = w[0] / np.linalg.norm(w[0])
    angle = np.arctan(u[1] / u[0])
    angle = 180 * angle / np.pi  # convert to degrees
    # filled Gaussian at 2 standard deviation
    ellipse = mpatches.Ellipse(xy=center, width=2 * v[0] ** 0.5,
                               height=2 * v[1] ** 0.5, angle=180 + angle,
                               facecolor=facecolor, edgecolor=edgecolor,
                               linewidth=2, zorder=2)
    ellipse.set_clip_box(ax.bbox)
    ellipse.set_alpha(0.5)
    ax.add_artist(ellipse)
    return ellipse


############################################################################ 
Example 74
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 75
Project: linear_neuron   Author: uglyboxer   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 76
Project: MuMoT   Author: DiODeProject   File: views.py    GNU General Public License v3.0 4 votes vote down vote up
def _plot_point_cov(
        points: np.ndarray,
        nstd: Optional[float] = 2,
        ax: Optional[matplotlib.axes.Axes] = None,
        **kwargs) -> matplotlib.patches.Ellipse:
    """
    Plots an ``nstd`` sigma ellipse based on the mean and covariance of a point
    "cloud" (``points``, an Nx2 array).

    Parameters
    ----------
    points : numpy.ndarray
        An Nx2 array of the data points.
    nstd : float, optional
        The radius of the ellipse in numbers of standard deviations.
        Defaults to 2 standard deviations.
    ax : matplotlib.axes.Axes, optional
        The axis that the ellipse will be plotted on. Defaults to the
        current axis.

    Returns
    -------
    :class:`matplotlib.patches.Ellipse`
        A matplotlib ellipse artist

    Notes
    -----
    Additional keyword arguments are pass on to the ellipse patch.

    Credit
    ------
    https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
    """
    # Copyright (c) 2012 Free Software Foundation
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy of
    # this software and associated documentation files (the "Software"), to deal in
    # the Software without restriction, including without limitation the rights to
    # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
    # of the Software, and to permit persons to whom the Software is furnished to do
    # so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    # SOFTWARE.
    pos = points.mean(axis=0)
    cov = np.cov(points, rowvar=False)
    return _plot_cov_ellipse(cov, pos, nstd, ax, **kwargs) 
Example 77
Project: calin   Author: sguiz   File: dnaplotlib.py    MIT License 4 votes vote down vote up
def trace_rbs (ax, type, num, start_bp, end_bp, prev_end, scale, linewidth, opts):
    """ Built-in trace-based ribosome binding site renderer.
    """
    # Default options
    zorder_add = 0.0
    color = (0.16,0.68,0.15)
    y_offset = 0.0
    y_extent = 3.5
    x_extent = 10.0
    highlight_y_extent = 0.8
    # Reset defaults if provided
    if opts != None:
        if 'zorder_add' in list(opts.keys()):
            zorder_add = opts['zorder_add']
        if 'color' in list(opts.keys()):
            color = opts['color']
        if 'y_offset' in list(opts.keys()):
            y_offset = opts['y_offset']
        if 'y_extent' in list(opts.keys()):
            y_extent = opts['y_extent']
        if 'x_extent' in list(opts.keys()):
            x_extent = opts['x_extent']
        if 'highlight_y_extent' in list(opts.keys()):
            highlight_y_extent = opts['highlight_y_extent']
        if 'linewidth' in list(opts.keys()):
            linewidth = opts['linewidth']
        if 'scale' in list(opts.keys()):
            scale = opts['scale']
    # Check direction add start padding
    dir_fac = 1.0
    if start_bp > end_bp:
        dir_fac = -1.0
    # Draw the RBS symbol
    l1 = Line2D([start_bp,start_bp],[0+y_offset,dir_fac*y_extent+y_offset], linewidth=linewidth, color=color, zorder=14+zorder_add)
    ax.add_line(l1)
    c1 = Ellipse((start_bp,dir_fac*y_extent+y_offset),width=(x_extent*scale),height=y_extent*0.4,color=color, zorder=14+zorder_add)
    ax.add_artist(c1)
    # Shade the promoter area (normally smaller than symbol extent)
    p2 = Polygon([(start_bp, -highlight_y_extent+y_offset), 
                  (start_bp, highlight_y_extent+y_offset),
                  (end_bp, highlight_y_extent+y_offset),
                  (end_bp, -highlight_y_extent+y_offset)], facecolor=color, edgecolor=color, linewidth=linewidth, zorder=14+zorder_add, 
                  path_effects=[Stroke(joinstyle="miter")]) # This is a work around for matplotlib < 1.4.0)
    ax.add_patch(p2)
    if opts != None and 'label' in list(opts.keys()):
        if start_bp > end_bp:
            write_label(ax, opts['label'], end_bp+((start_bp-end_bp)/2.0), opts=opts)
        else:
            write_label(ax, opts['label'], start_bp+((end_bp-start_bp)/2.0), opts=opts)
    if start_bp > end_bp:
        return end_bp, start_bp
    else:
        return start_bp, end_bp 
Example 78
Project: psychrometric-chart-makeover   Author: buds-lab   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 79
Project: MIM   Author: seraphlabs-ca   File: auxiliary.py    MIT License 4 votes vote down vote up
def plot(self, N=None, dims=[0, 1], label=None, **kwargs):
        """
        Plot a representation of the distribution.

        N - number of samples to return.
        dims - dimensions to visualize
        """
        defaults = dict(
            edgecolor="k",
            facecolor='none',
            ls="--",
            lw=5.0,
            alpha=1.0,
        )

        defaults.update(kwargs)

        N = min(N, self.scale.shape[0])
        scale = self.scale[:N]
        loc = self.loc[:N]

        b = loc.shape[0]
        d = loc.shape[1]

        dims = [min(d, cur_dim) for cur_dim in dims]

        ax = plt.gca()
        all_h = []
        for i in range(b):
            w, h = (max(v, 0.01) for v in scale[i, dims])
            ell = Ellipse(
                xy=loc[i, dims],
                width=w * 2,
                height=h * 2,
                **defaults
            )

            ax.add_patch(ell)
            all_h.append(ell)

        if label is not None:
            ell.set(label=label)

        return all_h 
Example 80
Project: catplot   Author: PytLab   File: ep_canvas.py    MIT License 4 votes vote down vote up
def add_energy_annotations(self, ep_line):
        """ Add energy related annotations to a specific energy profile line.

        Parameters:
        -----------
        ep_line: EPLine object, the energy profile line.
        """
        eigen_pts = ep_line.eigen_points

        # Energy latex strings.
        if eigen_pts.has_barrier:
            act_energy_latex = r"$\bf{G_{a} = " + str(ep_line.energies[1]) + r" eV}$"
        rxn_energy_latex = r"$\bf{\Delta G = " + str(ep_line.energies[-1]) + r" eV}$"

        el = Ellipse((2, -1), 0.5, 0.5)

        if eigen_pts.has_barrier:
            # Text annotation for barrier.
            x = eigen_pts.C[0]
            y = (eigen_pts.B[1] + eigen_pts.C[1])/2.0
            self.axes.annotate(act_energy_latex,
                               xy=(x, y),
                               xytext=(-150, 30),
                               textcoords="offset points",
                               size=13,
                               color="#B22222",
                               arrowprops=dict(arrowstyle="simple",
                                               fc="0.6",
                                               ec="none",
                                               patchB=el,
                                               connectionstyle="arc3,rad=0.2"))

        # Text annotation for reaction energy.
        x = (eigen_pts.D[0] + eigen_pts.E[0])/2.0
        y = (eigen_pts.D[1] + eigen_pts.B[1])/2.0
        self.axes.annotate(rxn_energy_latex,
                           xy=(x, y),
                           xytext=(50, 30),
                           textcoords="offset points",
                           size=13,
                           color="#8E388E",
                           arrowprops=dict(arrowstyle="simple",
                                           fc="0.6",
                                           ec="none",
                                           patchB=el,
                                           connectionstyle="arc3,rad=0.2"))

        return self