我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用matplotlib.patches.Ellipse()。
def plot_ellipse(ax, mu, sigma, color="k"): """ Based on http://stackoverflow.com/questions/17952171/not-sure-how-to-fit-data-with-a-gaussian-python. """ # Compute eigenvalues and associated eigenvectors vals, vecs = np.linalg.eigh(sigma) # Compute "tilt" of ellipse using first eigenvector x, y = vecs[:, 0] theta = np.degrees(np.arctan2(y, x)) # Eigenvalues give length of ellipse along each eigenvector w, h = 2 * np.sqrt(vals) ax.tick_params(axis='both', which='major', labelsize=20) ellipse = Ellipse(mu, w, h, theta, color=color) # color="k") ellipse.set_clip_box(ax.bbox) ellipse.set_alpha(0.2) ax.add_artist(ellipse)
def plot_ellipse(ax, mu, sigma, color="b"): """ Based on http://stackoverflow.com/questions/17952171/not-sure-how-to-fit-data-with-a-gaussian-python. """ # Compute eigenvalues and associated eigenvectors vals, vecs = np.linalg.eigh(sigma) # Compute "tilt" of ellipse using first eigenvector x, y = vecs[:, 0] theta = np.degrees(np.arctan2(y, x)) # Eigenvalues give length of ellipse along each eigenvector w, h = 2 * np.sqrt(vals) ellipse = Ellipse(mu, w, h, theta, color=color) # color="k") ellipse.set_clip_box(ax.bbox) ellipse.set_alpha(0.2) ax.add_artist(ellipse)
def draw_group(data, panel_params, coord, ax, **params): data = coord.transform(data, panel_params) fill = to_rgba(data['fill'], data['alpha']) color = to_rgba(data['color'], data['alpha']) ranges = coord.range(panel_params) # For perfect circles the width/height of the circle(ellipse) # should factor in the dimensions of axes bbox = ax.get_window_extent().transformed( ax.figure.dpi_scale_trans.inverted()) ax_width, ax_height = bbox.width, bbox.height factor = ((ax_width/ax_height) * np.ptp(ranges.y)/np.ptp(ranges.x)) size = data.loc[0, 'binwidth'] * params['dotsize'] offsets = data['stackpos'] * params['stackratio'] if params['binaxis'] == 'x': width, height = size, size*factor xpos, ypos = data['x'], data['y'] + height*offsets elif params['binaxis'] == 'y': width, height = size/factor, size xpos, ypos = data['x'] + width*offsets, data['y'] circles = [] for xy in zip(xpos, ypos): patch = mpatches.Ellipse(xy, width=width, height=height) circles.append(patch) coll = mcoll.PatchCollection(circles, edgecolors=color, facecolors=fill) ax.add_collection(coll)
def make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False): fig = ax.get_figure() def axes2pt(): return np.diff( ax.transData.transform([(0,0), (1,1)]), axis=0)[0] * (72./fig.dpi) ellipses = [] if not dont_resize_actively: def update_width_height(event): dist = axes2pt() for e, radius in ellipses: e.width, e.height = 2. * radius * dist fig.canvas.mpl_connect('resize_event', update_width_height) ax.callbacks.connect('xlim_changed', update_width_height) ax.callbacks.connect('ylim_changed', update_width_height) def legend_circle_handler(legend, orig_handle, xdescent, ydescent, width, height, fontsize): w, h = 2. * orig_handle.get_radius() * axes2pt() e = Ellipse(xy=(0.5*width-0.5*xdescent, 0.5*height-0.5*ydescent), width=w, height=w) ellipses.append((e, orig_handle.get_radius())) return e return {Circle: HandlerPatch(patch_func=legend_circle_handler)}
def plot_scatter(ax, x, y, s=5, c='black', label='', plot_training_cov=False, model=None): assert len(x.shape) == 1 assert len(y.shape) == 1 if plot_training_cov is True: assert model is not None ax.scatter(x, y, c=c, s=s, label=label) if plot_training_cov is True: cov = model.data[label]['cov'] mean_x, mean_y = model.data[label]['mean'] w, h, deg = cov_ellipse(cov, nsig=2) ell = Ellipse(xy=(mean_x, mean_y), width=w, height=h, angle=deg, linewidth=2) ell.set_facecolor('none') ell.set_edgecolor('black') ax.add_patch(ell) ax.set_aspect('equal') return ax
def error_ellipse(mu, cov, ax=None, factor=1.0, **kwargs): """ Plot the error ellipse at a point given its covariance matrix. """ # some sane defaults facecolor = kwargs.pop('facecolor', 'none') edgecolor = kwargs.pop('edgecolor', 'k') x, y = mu U, S, V = np.linalg.svd(cov) theta = np.degrees(np.arctan2(U[1, 0], U[0, 0])) ellipsePlot = Ellipse(xy=[x, y], width=2 * np.sqrt(S[0]) * factor, height=2 * np.sqrt(S[1]) * factor, angle=theta, facecolor=facecolor, edgecolor=edgecolor, **kwargs) if ax is None: ax = plt.gca() ax.add_patch(ellipsePlot) return ellipsePlot
def error_ellipse(mu, cov, ax=None, factor=1.0, **kwargs): """ Plot the error ellipse at a point given its covariance matrix. """ # some sane defaults facecolor = kwargs.pop('facecolor', 'none') edgecolor = kwargs.pop('edgecolor', 'k') x, y = mu U, S, V = np.linalg.svd(cov) theta = np.degrees(np.arctan2(U[1, 0], U[0, 0])) ellipsePlot = Ellipse(xy=[x, y], width=2 * np.sqrt(S[0]) * factor, height=2 * np.sqrt(S[1]) * factor, angle=theta, facecolor=facecolor, edgecolor=edgecolor, **kwargs) if ax is None: ax = pl.gca() ax.add_patch(ellipsePlot) return ellipsePlot
def annotate_target(ra, dec, text, ha='left', size=120, color='black', extended=False, globular=False, padding=0.22, zorder=999): if extended: padding = 1.82 * padding el = Ellipse((ra, dec), width=0.5, height=0.18, zorder=zorder-1, facecolor='#888888', edgecolor=color, lw=2.) pl.axes().add_artist(el) elif globular: pl.scatter(ra, dec, zorder=zorder-1, marker='o', lw=1.7, s=size, edgecolor=color, color="None") pl.scatter(ra, dec, zorder=zorder-1, marker='+', lw=1.7, s=size, c=color) else: pl.scatter(ra, dec, zorder=zorder-1, marker='o', lw=0, s=size, c=color) if ha == 'left': padding = -padding text = pl.text(ra + padding, dec, text, zorder=zorder, fontsize=22, va='center', ha=ha, color=color) text.set_path_effects([path_effects.Stroke(linewidth=4, foreground='white'), path_effects.Normal()])
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
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 ))
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
def annotate_ellipse(params, ax=None, crop_radius=1.2, **kwargs): """Annotates an ellipse on an image Parameters ---------- params : tuple or dict either (yr, xr, yc, xc) tuple or dict with names ['yr', 'xr', 'yc', 'xc'] """ from matplotlib.patches import Ellipse ellipse_style = dict(ec='yellow', fill=False) ellipse_style.update(kwargs) if isinstance(params, tuple): yr, xr, yc, xc = params else: yr = params['yr'] xr = params['xr'] yc = params['yc'] xc = params['xc'] ax.add_artist(Ellipse(xy=(xc, yc), width=xr*2, height=yr*2, **ellipse_style)) # crop image around ellipse ax.set_xlim(xc - crop_radius * xr, xc + crop_radius * xr) ax.set_ylim(yc + crop_radius * yr, yc - crop_radius * yr) return ax
def annotate_ellipsoid(params, axs=None, crop_radius=1.2, **kwargs): """Annotates an ellipse on an image Parameters ---------- params : tuple or dict either (zr, yr, xr, zc, yc, xc) tuple or dict with names ['zr', 'yr', 'xr', 'zc', 'yc', 'xc'] """ from matplotlib.patches import Ellipse ellipse_style = dict(ec='yellow', fill=False) ellipse_style.update(kwargs) ax_xy, ax_zy, ax_zx, ax_extra = axs if isinstance(params, tuple): zr, yr, xr, zc, yc, xc = params else: zr = params['zr'] yr = params['yr'] xr = params['xr'] zc = params['zc'] yc = params['yc'] xc = params['xc'] ax_xy.add_artist(Ellipse(xy=(xc, yc), width=xr*2, height=yr*2, **ellipse_style)) ax_zy.add_artist(Ellipse(xy=(zc, yc), width=zr*2, height=yr*2, **ellipse_style)) ax_zx.add_artist(Ellipse(xy=(xc, zc), width=xr*2, height=zr*2, **ellipse_style)) # crop image around ellipse ax_xy.set_xlim(xc - crop_radius * xr, xc + crop_radius * xr) ax_xy.set_ylim(yc - crop_radius * yr, yc + crop_radius * yr) ax_zy.set_xlim(zc - crop_radius * zr, zc + crop_radius * zr) return axs
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))
def draw_nodes(self): """ Draw nodes to screen. """ node_r = 1 for i, node in enumerate(self.nodes): x = self.node_coords['x'][i] y = self.node_coords['y'][i] color = self.node_colors[i] node_patch = patches.Ellipse((x, y), node_r, node_r, lw=0, color=color, zorder=2) self.ax.add_patch(node_patch)
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]
def plot_ellipse(cov, mean, color): angle, width, height = equiprobable_ellipse(cov) e = Ellipse(xy=mean, width=width, height=height, angle=np.degrees(angle), ec=color, fc="none", lw=3, ls="dashed") plt.gca().add_artist(e)
def ellipse(ra, rb, ang, x0, y0): theta = np.arange(0.0, 360.0, 1.0) * np.pi / 180.0 xcenter, ycenter = x0, y0 width = 2*ra height = 2*rb x = width * np.cos(theta) y = height * np.sin(theta) rtheta = np.radians(ang) rotation_matrix = np.array([ [np.cos(rtheta), -np.sin(rtheta)], [np.sin(rtheta), np.cos(rtheta)], ]) x, y = np.dot(rotation_matrix, np.array([x, y])) x += xcenter y += ycenter e1 = patches.Ellipse((xcenter, ycenter), width, height, angle=ang, linewidth=1, fill=False, linestyle='--', edgecolor='black') return e1
def to_mpl_patch(self): """ This function ... :return: """ return mpl_Ellipse((self.center.x, self.center.y), self.major_axis_length, self.minor_axis_length, self.angle.to("deg").value, edgecolor='green', facecolor='none', lw=3, alpha=0.7) # -----------------------------------------------------------------
def draw_ellipse(fig, ax, x, y, w, h, a, fillcolor, bordercolor): e = patches.Ellipse( xy=(x, y), width=w, ls='solid', lw=1.0, ec=bordercolor, height=h, angle=a, color=fillcolor) ax.add_patch(e)
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)
def plot_cov_ellipse(cov, pos, nstd=2, **kwargs): """Plot confidence ellipse.""" r1, r2, theta = cov_ellipse(cov, nstd) ellip = Ellipse(xy=pos, width=2*r1, height=2*r2, angle=theta, **kwargs) plt.gca().add_artist(ellip) return ellip
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
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
def draw_ellipse(fig, ax, x, y, w, h, a, fillcolor): e = patches.Ellipse( xy=(x, y), width=w, height=h, angle=a, color=fillcolor) ax.add_patch(e)
def run(n, gen, figpos, xlabel, ylabel, xlo, xhi, ylo, yhi): obs = gen(n) s = SPN(3, 1, SPNParams(mvmaxscope=0)) s.update(obs) s.display() ells = [] for x in s.root.children[0].children[0].children[1].children: if x.children[0].index == 0: c2, c1 = x.children else: c1, c2 = x.children ell = Ellipse(xy=[c1.mean, c2.mean], width=np.sqrt(c1.var), height=np.sqrt(c2.var), fill=False, linewidth=3, zorder=2, color='r') ells.append(ell) fig = plt.figure(0) ax = fig.add_subplot(figpos, aspect='equal') ax.plot(obs[:,1], obs[:,0], '.') for e in ells: ax.add_artist(e) ax.set_xlim(xlo, xhi) ax.set_ylim(ylo, yhi) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel)
def plotHeadOutline(ax=None, radius=1.2): result = {} # if new axis not given, create one if ax is None: fig = plt.figure(figsize=(11,8)) result['fig'] = fig ax = fig.add_subplot(1,1,1, aspect='equal') result['ax'] = ax extent = (-0.16-radius,0.16+radius,-0.01-radius,0.20+radius) result['extent'] = extent ax.set_aspect('equal') ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) leftEar = pltPatches.Ellipse((-0.075-radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) ax.add_patch(leftEar) rightEar = pltPatches.Ellipse((0.075+radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) ax.add_patch(rightEar) result['leftEar'] = leftEar result['rightEar'] = rightEar noseLength = 0.18 noseWidth = 0.12 noseIntersect = 2.0*radius-np.sqrt(noseWidth**2+radius**2) leftNose, = ax.plot((0.0,-noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10) rightNose, = ax.plot((0.0,noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10) leftNose.set_solid_capstyle('round') rightNose.set_solid_capstyle('round') result['leftNose'] = leftNose result['rightNose'] = rightNose head = pltPatches.Circle((0.0,0.0), radius, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False) result['head'] = head ax.add_patch(head) ax.set_xticks([]) ax.set_yticks([]) return result
def create_patches(self): """ This function ... :return: """ colors = iter(pretty_colors) # Loop over the geometries for label in self.geometries: geometry = self.geometries[label] x_center = 0.0 y_center = 0.0 major = None # 2 * major axis radius minor = None # 2 * minor axis radius angle = None # in degrees if isinstance(geometry, SersicModel): major = 2.0 * geometry.effective_radius.to("pc").value minor = geometry.flattening * major angle = geometry.tilt.to("deg").value elif isinstance(geometry, ExponentialDiskModel): major = 2.0 * geometry.radial_scale.to("pc").value minor = 2.0 * geometry.axial_scale.to("pc").value angle = geometry.tilt.to("deg").value elif isinstance(geometry, DeprojectionModel): minor = 2.0 * geometry.scale_height.to("pc").value major = 0.3 * (geometry.pixelscale * geometry.x_size).to("pc").value angle = 0.0 if self._min_x is None or 0.5*major > abs(self._min_x): self._min_x = - 0.5*major if self._max_x is None or 0.5*major > self._max_x: self._max_x = 0.5*major if self._min_y is None or 0.5*minor > abs(self._min_y): self._min_y = - 0.5*minor if self._max_y is None or 0.5*minor > self._max_y: self._max_y = 0.5*minor # Create the patch color = next(colors) ell = plt_Ellipse((x_center, y_center), major, minor, angle, edgecolor='none', facecolor=color, lw=3, alpha=0.7) # Add the patch self.patches[label] = ell # -----------------------------------------------------------------
def gen_ellip(h, k, a, b, mu, graph=True): ''' -------------------------------------------------------------------- This plots the general functional form of an ellipse and highlights the upper-right quadrant. [([x - h] / a) ** mu] + [([y - k] / b) ** mu] = 1 -------------------------------------------------------------------- INPUTS: h = scalar, x-coordinate of centroid (h, k) k = scalar, y-coordinate of centroid (h, k) a = scalar > 0, horizontal radius of ellipse b = scalar > 0, vertical radius of ellipse mu = scalar > 0, curvature parameter of ellipse graph = boolean, =True if graph output OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None OBJECTS CREATED WITHIN FUNCTION: N = integer > 0, number of elements in the support of x xvec = (N,) vector, support of x variable yvec = (N,) vector, values of y corresponding to the upper-right quadrant values of the ellipse from xvec FILES CREATED BY THIS FUNCTION: images/EllipseGen.png RETURNS: xvec, yvec -------------------------------------------------------------------- ''' N = 1000 xvec = np.linspace(h, h + a, N) yvec = b * ((1 - (((xvec - h) / a) ** mu)) ** (1 / mu)) + k if graph: e1 = Ellipse((h, k), 2 * a, 2 * b, 360.0, linewidth=2.0, fill=False, label='Full ellipse') fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') ax.add_patch(e1) plt.plot(xvec, yvec, color='r', linewidth=4, label='Upper-right quadrant') # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.xlabel(r'$x$') plt.ylabel(r'$y$') plt.xlim((h - 1.6 * a, h + 1.6 * a)) plt.ylim((k - 1.4 * b, k + 1.4 * b)) # plt.legend(loc='upper right') figname = "images/EllipseGen" plt.savefig(figname) print("Saved figure: " + figname) # plt.show() plt.close() return xvec, yvec
def plot_x_with_mulpart_and_twiss(multipartin, twissin, multipartout, twissout, emittance_x): xin = [multipartin[i][0][0] for i in xrange(len(multipartin))] xpin = [multipartin[i][0][1] for i in xrange(len(multipartin))] beta_x_in = twissin[0] alpha_x_in = twissin[1] gamma_x_in = twissin[2] a = math.sqrt(emittance_x*beta_x_in) b = math.sqrt(emittance_x*gamma_x_in) phi = 1/2*math.atan(2*alpha_x_in/(gamma_x_in-beta_x_in)) xo = [multipartout[i][0][0] for i in xrange(len(multipartout))] xpo = [multipartout[i][0][1] for i in xrange(len(multipartout))] beta_x_out = twissout[0] alpha_x_out = twissout[1] gamma_x_out = twissout[2] a_after = math.sqrt(emittance_x*beta_x_out) b_after = math.sqrt(emittance_x*gamma_x_out) phi_after = 1/2*math.atan(2*alpha_x_out/(gamma_x_out-beta_x_out)) ellipse_x = Ellipse((0,0), 2*a, 2*b, -phi*180/constants.pi, linewidth=5) ellipse_x.set_facecolor('none') ellipse_x.set_edgecolor((0,0,1)) ellipse_x_after = Ellipse((0,0), 2*a_after, 2*b_after, -phi_after*180/constants.pi, linewidth=5) ellipse_x_after.set_facecolor('none') ellipse_x_after.set_edgecolor((0,0,1)) plt.figure(0) ax1 = plt.subplot2grid((1,2), (0,0)) ax1.add_artist(ellipse_x) ax1.plot(xin,xpin,'ro', zorder=1) plt.title('Initial values in x') plt.xlabel('x [m]') plt.ylabel('x\' []') ax2 = plt.subplot2grid((1,2), (0, 1)) ax2.add_artist(ellipse_x_after) ax2.plot(xo,xpo,'ro', zorder=1) #ax2.set_xlim(-0.004, 0.004) #ax2.set_ylim(-0.004, 0.004) plt.title('Values after all elems in lattice in x') plt.xlabel('x [m]') plt.ylabel('x\' []') plt.show()
def __drawActualLandMark(self, aAx): """"?????????? ??? aAx????? ???? ?? """ flag = False obsCrnt = self.__mObsActu[-1] poseCrnt = self.__mPosesActu[-1] lst_px = [] lst_py = [] soa = [] if len(obsCrnt) != 0: for obs in obsCrnt: obsDist = obs.getDist() obsDir = obs.getDir() lmCovM = self.__mScnSnsr.getLandMarkCovMatrixOnMeasurementSys(obsDist) lmCovW = self.__mScnSnsr.tfMeasurement2World(lmCovM, obsDir, poseCrnt[2, 0]) Pxy = lmCovW[0:2, 0:2] x, y, ang_rad = self.__mEllipse.calc_error_ellipse(Pxy) px = (obsDist * np.cos(obsDir + poseCrnt[2, 0] - tf.BASE_ANG)) + poseCrnt[0, 0] py = (obsDist * np.sin(obsDir + poseCrnt[2, 0] - tf.BASE_ANG)) + poseCrnt[1, 0] p = (px, py) # ?????? if flag == False: ellLbl = "Error Ellipse: %.2f[%%]" % self.__mConfidence_interval else: ellLbl = "" e = patches.Ellipse(p, x, y, angle=np.rad2deg(ang_rad), linewidth=2, alpha=0.2, facecolor='yellow', edgecolor='black', label=ellLbl) aAx.add_patch(e) lst_px.append(px) lst_py.append(py) # ????-??????????? ps = poseCrnt[0:2, 0].T xl = np.array([ps[0], px]) yl = np.array([ps[1], py]) soa.append([ps[0], ps[1], px - ps[0], py - ps[1]]) aAx.plot(xl, yl, '--', c='green') flag = True # ?????????? aAx.scatter(lst_px, lst_py, s=100, c="red", marker="*", alpha=0.5, linewidths="2", edgecolors="red", label="Land Mark(Actual)")
def animate(i, ekf, period_ms): global P1, P2, P3, P2 global time_s col_x_true = 'red' # col_x_dr = 'yellow' col_z = 'green' col_x_hat = 'blue' time_s += period_ms / 1000 x_true, x_dr, obs, x_pre, P = ekf.main_ekf() plt.cla() ax1 = plt.subplot2grid((1, 1), (0, 0)) # ??x(??)??? P1.append(x_true[0:2, :]) a, b = np.array(np.concatenate(P1, axis=1)) ax1.plot(a, b, c=col_x_true, linewidth=1.0, linestyle='-', label='Ground Truth') ax1.scatter(x_true[0], x_true[1], c=col_x_true, marker='o', alpha=0.5) # ??x(????????)??? # P2.append(x_dr) # a, b, c = np.array(np.concatenate(P2, axis=1)) # ax1.plot(a, b, c=col_x_dr, linewidth=1.0, linestyle='-', label='Dead Reckoning') # ax1.scatter(x_dr[0], x_dr[1], c=col_x_dr, marker='o', alpha=0.5) # ??z??? P3.append(obs) a, b = np.array(np.concatenate(P3, axis=1)) ax1.scatter(a, b, c=col_z, marker='o', alpha=0.5, label='Observation') # ??x(???)??? P2.append(x_pre[0:2, :]) a, b = np.array(np.concatenate(P2, axis=1)) ax1.plot(a, b, c=col_x_hat, linewidth=1.0, linestyle='-', label='Predicted') ax1.scatter(x_pre[0], x_pre[1], c=col_x_hat, marker='o', alpha=0.5) # ?????? Pxy = P[0:2, 0:2] x, y, ang_rad = ee.calc_error_ellipse(Pxy) e = patches.Ellipse((x_pre[0, 0], x_pre[1, 0]), x, y, angle=np.rad2deg(ang_rad), linewidth=2, alpha=0.2, facecolor='yellow', edgecolor='black', label='Error Ellipse: %.2f[%%]' % confidence_interval) print('time:{0:.3f}[s], x-cov:{1:.3f}[m], y-cov:{2:.3f}[m], xy-cov:{3:.3f}[m]' .format(time_s, P[0, 0], P[1, 1], P[1, 0])) ax1.add_patch(e) ax1.set_xlabel('x [m]') ax1.set_ylabel('y [m]') ax1.set_title('Localization by EKF') ax1.axis('equal', adjustable='box') ax1.grid() ax1.legend(fontsize=10)