def scatter(self, x, y, xerr=None, yerr=None, cov=None, corr=None, s_expr=None, c_expr=None, labels=None, selection=None, length_limit=50000, length_check=True, label=None, xlabel=None, ylabel=None, errorbar_kwargs={}, ellipse_kwargs={}, **kwargs): """Convenience wrapper around pylab.scatter when for working with small datasets or selections :param x: Expression for x axis :param y: Idem for y :param s_expr: When given, use if for the s (size) argument of pylab.scatter :param c_expr: When given, use if for the c (color) argument of pylab.scatter :param labels: Annotate the points with these text values :param selection: Single selection expression, or None :param length_limit: maximum number of rows it will plot :param length_check: should we do the maximum row check or not? :param label: label for the legend :param xlabel: label for x axis, if None .label(x) is used :param ylabel: label for y axis, if None .label(y) is used :param errorbar_kwargs: extra dict with arguments passed to plt.errorbar :param kwargs: extra arguments passed to pylab.scatter :return: """ import pylab as plt x = _ensure_strings_from_expressions(x) y = _ensure_strings_from_expressions(y) label = str(label or selection) selection = _ensure_strings_from_expressions(selection) if length_check: count = self.count(selection=selection) if count > length_limit: raise ValueError("the number of rows (%d) is above the limit (%d), pass length_check=False, or increase length_limit" % (count, length_limit)) x_values = self.evaluate(x, selection=selection) y_values = self.evaluate(y, selection=selection) if s_expr: kwargs["s"] = self.evaluate(s_expr, selection=selection) if c_expr: kwargs["c"] = self.evaluate(c_expr, selection=selection) plt.xlabel(xlabel or self.label(x)) plt.ylabel(ylabel or self.label(y)) s = plt.scatter(x_values, y_values, label=label, **kwargs) if labels: label_values = self.evaluate(labels, selection=selection) for i, label_value in enumerate(label_values): plt.annotate(label_value, (x_values[i], y_values[i])) xerr_values = None yerr_values = None if cov is not None or corr is not None: from matplotlib.patches import Ellipse sx = self.evaluate(xerr, selection=selection) sy = self.evaluate(yerr, selection=selection) if corr is not None: sxy = self.evaluate(corr, selection=selection) * sx * sy elif cov is not None: sxy = self.evaluate(cov, selection=selection) cov_matrix = np.zeros((len(sx), 2, 2)) cov_matrix[:,0,0] = sx**2 cov_matrix[:,1,1] = sy**2 cov_matrix[:,0,1] = cov_matrix[:,1,0] = sxy ax = plt.gca() ellipse_kwargs = dict(ellipse_kwargs) ellipse_kwargs['facecolor'] = ellipse_kwargs.get('facecolor', 'none') ellipse_kwargs['edgecolor'] = ellipse_kwargs.get('edgecolor', 'black') for i in range(len(sx)): eigen_values, eigen_vectors = np.linalg.eig(cov_matrix[i]) indices = np.argsort(eigen_values)[::-1] eigen_values = eigen_values[indices] eigen_vectors = eigen_vectors[:,indices] v1 = eigen_vectors[:, 0] v2 = eigen_vectors[:, 1] varx = cov_matrix[i, 0, 0] vary = cov_matrix[i, 1, 1] angle = np.arctan2(v1[1], v1[0]) # round off errors cause negative values? if eigen_values[1] < 0 and abs((eigen_values[1]/eigen_values[0])) < 1e-10: eigen_values[1] = 0 if eigen_values[0] < 0 or eigen_values[1] < 0: raise ValueError('neg val') width, height = np.sqrt(np.max(eigen_values)), np.sqrt(np.min(eigen_values)) e = Ellipse(xy=(x_values[i], y_values[i]), width=width, height=height, angle=np.degrees(angle), **ellipse_kwargs) ax.add_artist(e) else: if xerr is not None: if _issequence(xerr): assert len(xerr) == 2, "if xerr is a sequence it should be of length 2" xerr_values = [self.evaluate(xerr[0], selection=selection), self.evaluate(xerr[1], selection=selection)] else: xerr_values = self.evaluate(xerr, selection=selection) if yerr is not None: if _issequence(yerr): assert len(yerr) == 2, "if yerr is a sequence it should be of length 2" yerr_values = [self.evaluate(yerr[0], selection=selection), self.evaluate(yerr[1], selection=selection)] else: yerr_values = self.evaluate(yerr, selection=selection) if xerr_values is not None or yerr_values is not None: errorbar_kwargs = dict(errorbar_kwargs) errorbar_kwargs['fmt'] = errorbar_kwargs.get('fmt', 'none') plt.errorbar(x_values, y_values, yerr=yerr_values, xerr=xerr_values, **errorbar_kwargs) return s
gain=1.0) # show the results: for i in range(len(objects1)): print("object {:d}: flux1 = {:f} +/- {:f}".format(i, flux1[i], fluxerr1[i])) # plot background-subtracted image fig, ax = plt.subplots() m, s = np.mean(data_sub1), np.std(data_sub1) im = ax.imshow(data_sub1, cmap='gray', vmin=m - s, vmax=m + s, origin='lower') # plot an ellipse for each object for i in range(len(objects1)): e = Ellipse(xy=(objects1['x'][i], objects1['y'][i]), width=6 * objects1['a'][i], height=6 * objects1['b'][i], angle=objects1['theta'][i] * 180. / np.pi) e.set_facecolor('none') e.set_edgecolor('red') ax.add_artist(e) '''Objects 2''' flux2, fluxerr2, flag2 = sep.sum_circle(data_sub2, objects2['x'], objects2['y'], 3.0, err=bkg2.globalrms, gain=1.0) # show the results: for i in range(len(objects2)): print("object {:d}: flux2 = {:f} +/- {:f}".format(i, flux2[i],
GX = GT * X GY = GT * Y GZ = GT * Z from matplotlib.patches import Ellipse, Circle import mpl_toolkits.mplot3d.art3d as art3d from matplotlib.collections import PatchCollection #ells = [Ellipse(xy=[x[i], y[i]], width=(0.6+0.4*rand())*(1.-0.5), height=0.6*1, angle=90, fill=False, lw=2) for i in range(len(psrs))] x = D * np.cos(gb) * np.sin(gl) y = solardist - D * np.cos(gb) * np.cos(gl) z = np.sin(gb) * D PeriAng = float(pf.OM[0]) Ang = PeriAng + gl * 180. / np.pi e = Ellipse(xy=[x, y], width=(0.9), height=0.5, angle=Ang, fill=True, lw=1) #ax.add_artist(ell) #p = PatchCollection([e]) #ax.add_collection3d(p, zs=[0]) #p = Circle((1,1),1) #ax.add_patch(p) ax.add_patch(e) art3d.pathpatch_2d_to_3d(e, z=z, zdir=(0.5, 0.5, 0.5)) e.set_alpha(1.) e.set_edgecolor('r') data = np.genfromtxt(open('log_arms.out', 'r'), dtype=[('Num', 'i'), ('n', 'i'), ('x', 'f8'), ('y', 'f8')])[1:] UniqNum = np.unique(data['Num']) for num in UniqNum:
def __init__(self, transform, width, height, angle, loc, pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs): """ Draw an anchored ellipse of a given size. Parameters ---------- transform : `matplotlib.transforms.Transform` The transformation object for the coordinate system in use, i.e., :attr:`matplotlib.axes.Axes.transData`. width, height : int or float Width and height of the ellipse, given in coordinates of *transform*. angle : int or float Rotation of the ellipse, in degrees, anti-clockwise. loc : int Location of this size bar. Valid location codes are:: 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10 pad : int or float, optional Padding around the ellipse, in fraction of the font size. Defaults to 0.1. borderpad : int or float, optional Border padding, in fraction of the font size. Defaults to 0.1. frameon : bool, optional If True, draw a box around the ellipse. Defaults to True. prop : `matplotlib.font_manager.FontProperties`, optional Font property used as a reference for paddings. **kwargs : Keyworded arguments to pass to :class:`matplotlib.offsetbox.AnchoredOffsetbox`. Attributes ---------- ellipse : `matplotlib.patches.Ellipse` Ellipse patch drawn. """ 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)
ax = plt.gca() ax.set_facecolor('xkcd:black') ax.grid(alpha=0.2) # Adjust the scale to fit the GPS coordinate # 160 Meter diameter latitude and longitude diameterLat = (1.0 / latToM) diameterLong = (1.0 / longToM) axisInM = 100.0 # The size of half the screen in meters ax.set_xlim(coordinates[1] - diameterLong * axisInM, coordinates[1] + diameterLong * axisInM) ax.set_ylim(coordinates[0] - diameterLat * axisInM, coordinates[0] + diameterLat * axisInM) # Create a ellipse from the GPS coordinates with different intervals (in meters) eIntervals = (20.0, 50.0, 100.0) ellipses = [Ellipse(xy = (coordinates[1], coordinates[0]), width = diameterLong * eInt, height = diameterLat * eInt, facecolor = 'none', edgecolor = 'w', lw = 0.5, alpha = 0.5) for eInt in eIntervals] # Add the ellipses to the plot for ellipse in ellipses: ax.add_artist(ellipse) # Remove white space padding fig.tight_layout() # Draw the plot to the screen plt.pause(0.01) plt.draw()
if max(pattern[2:7]) == 1: # right bar for j in range(7): if pattern[j] == 1: row = 7 - j ax.plot([space * (i + 1) + nmid * mid + 1.2] * 2, [row, row + 7], color="black") pre = 0 for k in range(j + 1, 7): if pattern[k] == 1: pre += 1 else: break if pre % 2 == 1: c = Ellipse([space * (i + 1) + nmid * mid + 2.4, row], width=2.5, height=1.8, angle=30, color="black") else: c = Ellipse([space * (i + 1) + nmid * mid, row], width=2.5, height=1.8, angle=30, color="black") ax.add_patch(c) elif max(pattern[:2]) == 1: # left bar for j in range(7): if pattern[j] == 1: row = 7 - j ax.plot([space * (i + 1) + nmid * mid - 1.2] * 2, [row - 7, row], color="black") pre = 0 for k in range(j): if pattern[k] == 1:
def learn(data_set, complexity_type): n_tasks = len(data_set) n_dim = data_set[0].shape[1] n_samples_list = [task_data.shape[0] for task_data in data_set] # Define prior: w_P_mu = Variable(torch.randn(n_dim).cuda(), requires_grad=True) w_P_log_sigma = Variable(torch.randn(n_dim).cuda(), requires_grad=True) # Init posteriors: w_mu = Variable(torch.randn(n_tasks, n_dim).cuda(), requires_grad=True) w_log_sigma = Variable(torch.randn(n_tasks, n_dim).cuda(), requires_grad=True) learning_rate = 1e-1 # create your optimizer optimizer = optim.Adam([w_mu, w_log_sigma, w_P_mu, w_P_log_sigma], lr=learning_rate) n_epochs = 800 batch_size = 128 for i_epoch in range(n_epochs): # Sample data batch: b_task = np.random.randint(0, n_tasks) # sample a random task index batch_size_curr = min(n_samples_list[b_task], batch_size) batch_inds = np.random.choice(n_samples_list[b_task], batch_size_curr, replace=False) task_data = torch.from_numpy(data_set[b_task][batch_inds]) task_data = Variable(task_data.cuda(), requires_grad=False) # Re-Parametrization: w_sigma = torch.exp(w_log_sigma[b_task]) epsilon = Variable(torch.randn(n_dim).cuda(), requires_grad=False) w = w_mu[b_task] + w_sigma * epsilon # Empirical Loss: empirical_loss = (w - task_data).pow(2).mean() # Complexity terms: sigma_sqr_prior = torch.exp(2 * w_P_log_sigma) complex_term_sum = 0 for i_task in range(n_tasks): sigma_sqr_post = torch.exp(2 * w_log_sigma[i_task]) kl_dist = torch.sum(w_P_log_sigma - w_log_sigma[i_task] + ( (w_mu[i_task] - w_P_mu).pow(2) + sigma_sqr_post) / (2 * sigma_sqr_prior) - 0.5) n_samples = n_samples_list[i_task] if complexity_type == 'PAC_Bayes_McAllaster': delta = 0.95 complex_term_sum += torch.sqrt( (1 / (2 * n_samples)) * (kl_dist + np.log(2 * np.sqrt(n_samples) / delta))) elif complexity_type == 'Variational_Bayes': complex_term_sum += (1 / n_samples) * kl_dist elif complexity_type == 'KL': complex_term_sum += kl_dist else: raise ValueError('Invalid complexity_type') hyper_prior_factor = 1e-6 * np.sqrt(1 / n_tasks) hyper_prior = torch.sum(sigma_sqr_prior + w_P_mu.pow(2)) * hyper_prior_factor # Total objective: complex_term = (1 / n_tasks) * complex_term_sum objective = empirical_loss + complex_term + hyper_prior # Gradient step: optimizer.zero_grad() # zero the gradient buffers objective.backward() optimizer.step() # Does the update if i_epoch % 100 == 0: print('Step: {0}, objective: {1}'.format(i_epoch, objective.data[0])) # Switch back to numpy: w_mu = w_mu.data.cpu().numpy() w_log_sigma = w_log_sigma.data.cpu().numpy() w_sigma = np.exp(w_log_sigma) w_P_mu = w_P_mu.data.cpu().numpy() w_P_log_sigma = w_P_log_sigma.data.cpu().numpy() w_P_sigma = np.exp(w_P_log_sigma) # Plots: fig1 = plt.figure() ax = plt.subplot(111, aspect='equal') # plot prior: plt.plot(w_P_mu[0], w_P_mu[1], 'o', label='prior mean ') ell = Ellipse(xy=(w_P_mu[0], w_P_mu[1]), width=w_P_sigma[0], height=w_P_sigma[1], angle=0, color='blue') ell.set_facecolor('none') ax.add_artist(ell) for i_task in range(n_tasks): # plot task data points: plt.plot(data_set[i_task][:, 0], data_set[i_task][:, 1], '.', label='Task {0} samples'.format(1 + i_task)) # plot posterior: plt.plot(w_mu[i_task][0], w_mu[i_task][1], 'o', label='posterior {0} mean'.format(1 + i_task)) ell = Ellipse(xy=(w_mu[i_task][0], w_mu[i_task][1]), width=w_sigma[i_task][0], height=w_sigma[i_task][1], angle=0, color='black') ell.set_facecolor('none') ax.add_artist(ell) # plt.plot(0, 0, 'x', label='hyper-prior ') # plt.legend(loc='upper left') plt.legend() plt.xlabel('Dimension 1') plt.ylabel('Dimension 2')
color='w', transform=ax.transAxes) plot_name = 'm82_03cm_map_B' elif MODE == 2: ax.text(0.05, 0.9, "Model B'", ha='left', va='bottom', color='w', transform=ax.transAxes) plot_name = 'm82_03cm_map_Bp' #beam from matplotlib.patches import Ellipse beam = Ellipse(xy=[80, -80], width=7.6, height=7.3) ax.add_artist(beam) beam.set_facecolor('white') beam.set_alpha(0.6) beam.set_zorder(90) # plot_name = 'm82_03cm_map_' for n in range(0, 100): if os.path.isfile(plot_name + str(n).zfill(2) + '.png'): continue else: plt.savefig(plot_name + str(n).zfill(2) + '.png', bbox_inches='tight', dpi=400) break
def plot(self, leaf_separation=1, cmap='viridis', select_clusters=False, label_clusters=False, selection_palette=None, axis=None, colorbar=True, log_size=False, max_rectangles_per_icicle=20): """Use matplotlib to plot an 'icicle plot' dendrogram of the condensed tree. Effectively this is a dendrogram where the width of each cluster bar is equal to the number of points (or log of the number of points) in the cluster at the given lambda value. Thus bars narrow as points progressively drop out of clusters. The make the effect more apparent the bars are also colored according the the number of points (or log of the number of points). Parameters ---------- leaf_separation : float, optional (default 1) How far apart to space the final leaves of the dendrogram. cmap : string or matplotlib colormap, optional (default viridis) The matplotlib colormap to use to color the cluster bars. select_clusters : boolean, optional (default False) Whether to draw ovals highlighting which cluster bar represent the clusters that were selected by HDBSCAN as the final clusters. label_clusters : boolean, optional (default False) If select_clusters is True then this determines whether to draw text labels on the clusters. selection_palette : list of colors, optional (default None) If not None, and at least as long as the number of clusters, draw ovals in colors iterating through this palette. This can aid in cluster identification when plotting. axis : matplotlib axis or None, optional (default None) The matplotlib axis to render to. If None then a new axis will be generated. The rendered axis will be returned. colorbar : boolean, optional (default True) Whether to draw a matplotlib colorbar displaying the range of cluster sizes as per the colormap. log_size : boolean, optional (default False) Use log scale for the 'size' of clusters (i.e. number of points in the cluster at a given lambda value). max_rectangles_per_icicle : int, optional (default 20) To simplify the plot this method will only emit ``max_rectangles_per_icicle`` bars per branch of the dendrogram. This ensures that we don't suffer from massive overplotting in cases with a lot of data points. Returns ------- axis : matplotlib axis The axis on which the 'icicle plot' has been rendered. """ try: import matplotlib.pyplot as plt except ImportError: raise ImportError( 'You must install the matplotlib library to plot the condensed tree.' 'Use get_plot_data to calculate the relevant data without plotting.' ) plot_data = self.get_plot_data( leaf_separation=leaf_separation, log_size=log_size, max_rectangle_per_icicle=max_rectangles_per_icicle) if cmap != 'none': sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize( 0, max(plot_data['bar_widths']))) sm.set_array(plot_data['bar_widths']) bar_colors = [sm.to_rgba(x) for x in plot_data['bar_widths']] else: bar_colors = 'black' if axis is None: axis = plt.gca() axis.bar(plot_data['bar_centers'], plot_data['bar_tops'], bottom=plot_data['bar_bottoms'], width=plot_data['bar_widths'], color=bar_colors, align='center', linewidth=0) drawlines = [] for xs, ys in zip(plot_data['line_xs'], plot_data['line_ys']): drawlines.append(xs) drawlines.append(ys) axis.plot(*drawlines, color='black', linewidth=1) # for xs, ys in zip(plot_data['line_xs'], plot_data['line_ys']): # axis.plot(xs, ys, color='black', linewidth=1) if select_clusters: try: from matplotlib.patches import Ellipse except ImportError: raise ImportError( 'You must have matplotlib.patches available to plot selected clusters.' ) chosen_clusters = self._select_clusters() # Extract the chosen cluster bounds. If enough duplicate data points exist in the # data the lambda value might be infinite. This breaks labeling and highlighting # the chosen clusters. cluster_bounds = np.array( [plot_data['cluster_bounds'][c] for c in chosen_clusters]) if not np.isfinite(cluster_bounds).all(): warn('Infinite lambda values encountered in chosen clusters.' ' This might be due to duplicates in the data.') # Extract the plot range of the y-axis and set default center and height values for ellipses. # Extremly dense clusters might result in near infinite lambda values. Setting max_height # based on the percentile should alleviate the impact on plotting. plot_range = np.hstack( [plot_data['bar_tops'], plot_data['bar_bottoms']]) plot_range = plot_range[np.isfinite(plot_range)] mean_y_center = np.mean([np.max(plot_range), np.min(plot_range)]) max_height = np.diff(np.percentile(plot_range, q=[10, 90])) for i, c in enumerate(chosen_clusters): c_bounds = plot_data['cluster_bounds'][c] width = (c_bounds[CB_RIGHT] - c_bounds[CB_LEFT]) height = (c_bounds[CB_TOP] - c_bounds[CB_BOTTOM]) center = ( np.mean([c_bounds[CB_LEFT], c_bounds[CB_RIGHT]]), np.mean([c_bounds[CB_TOP], c_bounds[CB_BOTTOM]]), ) # Set center and height to default values if necessary if not np.isfinite(center[1]): center = (center[0], mean_y_center) if not np.isfinite(height): height = max_height # Ensure the ellipse is visible min_height = 0.1 * max_height if height < min_height: height = min_height if selection_palette is not None and \ len(selection_palette) >= len(chosen_clusters): oval_color = selection_palette[i] else: oval_color = 'r' box = Ellipse(center, 2.0 * width, 1.2 * height, facecolor='none', edgecolor=oval_color, linewidth=2) if label_clusters: axis.annotate(str(i), xy=center, xytext=(center[0] - 4.0 * width, center[1] + 0.65 * height), horizontalalignment='left', verticalalignment='bottom') axis.add_artist(box) if colorbar: cb = plt.colorbar(sm) if log_size: cb.ax.set_ylabel('log(Number of points)') else: cb.ax.set_ylabel('Number of points') axis.set_xticks([]) for side in ('right', 'top', 'bottom'): axis.spines[side].set_visible(False) axis.invert_yaxis() axis.set_ylabel('$\lambda$ value') return axis
def main(): parser = argparse.ArgumentParser( description= "Process raw IPTS touch data and output image files for prototyping") parser.add_argument('file_in', metavar='INPUT', type=str, nargs=1, help='raw IPTS input data') parser.add_argument('file_out', metavar='OUTPUT', type=str, nargs=1, help='output image base name') args = parser.parse_args() time_start = datetime.datetime.now() print("Loading data...") with open(args.file_in[0], 'rb') as f: data = f.read() parser = TouchParser() heatmaps = parser.parse(data) fig, ax = plt.subplots() ax.axis('off') fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) fig.set_size_inches(12, 8) print("Processing...") ims = [] for i, hm in enumerate(heatmaps): elapsed = datetime.datetime.now() - time_start print( f" Frame {i+1}/{len(heatmaps)}, {((i + 1) / len(heatmaps)) * 100:.2f}%, elapsed: {elapsed}" ) # process hm = hm.T hm = preprocess(hm) hmf = filter(hm) ms = get_local_maximas(hmf) params_init = [(1.0, mu, np.identity(2)) for mu in ms] params_est = fit_multi(hmf, params_init, 3, drange=(3, 3)) params_est = [(mu, np.linalg.inv(sigma_inv)) for (c, mu, sigma_inv) in params_est if sigma_inv is not None] # plot nstd = 1.5 p = list() p.append(ax.imshow(hmf, vmin=0.0, vmax=0.3, animated=True)) p += ax.contour(hm, levels=[0.01], colors='black').collections p += ax.plot(ms[:, 1], ms[:, 0], 'b+', color='black', ms=11) for (mu, sigma) in params_est: eigvals, eigvecs = np.linalg.eigh(sigma) vx, vy = eigvecs[:, 0][0], eigvecs[:, 0][1] angle = np.arctan2(vx, vy) width, height = 2.0 * nstd * np.sqrt(eigvals) aspect = np.min([width, height]) / np.max([width, height]) if aspect < 0.45: continue p += ax.plot(mu[1], mu[0], 'b+', ms=10, color='red', animated=True) e = Ellipse(xy=(mu[1], mu[0]), width=width, height=height, angle=np.degrees(angle), facecolor='none', edgecolor='red') ax.add_artist(e) p.append(e) ims.append(p) print("Writing images...") an = animation.ArtistAnimation(fig, ims, interval=16.66, repeat_delay=1000, blit=True) file_out = args.file_out[0] dir_out = os.path.dirname(os.path.realpath(file_out)) os.makedirs(dir_out, exist_ok=True) an.save(file_out, writer='imagemagick') # rename files r = re.compile('(.+)-(\d+).(.+)') for file in os.listdir(dir_out): m = r.match(file) os.rename(f"{dir_out}/{file}", f"{dir_out}/{m[1]}-{int(m[2]):04d}.{m[3]}")
def drawrobot(xvec, color, type=2, W=.2, L=.6): """Draws a robot at a set pose using matplotlib in current plot Args: xvec (3x1 array): robot position and direction color (string or rbg or rgba array): color following matplotlib specs positions Kwargs: type (int [0:5]): dictates robot to be drawn with follow selections: - 0 : draws only a cross with orientation theta - 1 : draws a differential drive robot without contour - 2 : draws a differential drive robot with round shape - 3 : draws a round shaped robot with a line at theta - 4 : draws a differential drive robot with rectangular shape - 5 : draws a rectangular shaped robot with a line at theta W (float): robot width [m] L (float): robot length [m] Returns: h (list): matplotlib object list added to current axes """ theta = xvec[2] t = scipy.array([xvec[0], xvec[1]]) r = [] h = [] if type == 0: cs = .1 h += [ plt.plot([cs, -cs, None, 0., 0.] + t[0], [0., 0., None, cs, -cs] + t[1], color, lw=2.) ] elif type == 1: xy = W * scipy.array( (scipy.cos(theta + scipy.pi / 2), scipy.sin(theta + scipy.pi / 2))) temp = Rectangle(t + xy, .03, .02, color=color, angle=theta) h += [plt.gca().add_artist(temp)] temp = Rectangle(t - xy, .03, .02, color=color, angle=theta) h += [plt.gca().add_artist(temp)] rin = _rot(theta, scipy.array([0, W + .03])) temp = Arrow(xvec[0] - rin[0], xvec[1] - rin[1], rin[0], rin[1], color=color) h += [temp] plt.gca().add_artist(temp) elif type == 2: xy = W * scipy.array( (scipy.cos(theta + scipy.pi / 2), scipy.sin(theta + scipy.pi / 2))) temp = Rectangle(t + xy, .03, .02, color=color, angle=theta) plt.gca().add_artist(temp) temp = Rectangle(t - xy, .03, .02, color=color, angle=theta) plt.gca().add_artist(temp) #axis between wheels here (requires a rotation) # The lines from the matlab come with no explanation, but do matrix #math to yield a rotated arrow rin = _rot(theta, scipy.array([0, W + .015])) temp = Arrow(xvec[0] - rin[0], xvec[1] - rin[1], rin[0], rin[1], color=color) plt.gca().add_artist(temp) elif type == 3: temp = Ellipse(xvec[:2], W + .015, W + .015, angle=theta, color=color) plt.gca().add_artist(temp) rin = _rot(theta, scipy.array([W + .015, 0])) plt.plot(xvec[0] + scipy.array([-rin[0], rin[0]]), xvec[1] + scipy.array([-rin[1], rin[1]]), color=color, lw=2.) elif type == 4: xy = W * scipy.array( (scipy.cos(theta + scipy.pi / 2), scipy.sin(theta + scipy.pi / 2))) temp = Rectangle(t + xy, .03, .02, color=color, angle=theta) plt.gca().add_artist(temp) h += [temp] temp = Rectangle(t - xy, .03, .02, color=color, angle=theta) plt.gca().add_artist(temp) h += [temp] rin = _rot(theta, scipy.array([W + .015, 0])) h += [ plt.plot(xvec[0] + scipy.array([-rin[0], rin[0]]), xvec[1] + scipy.array([-rin[1], rin[1]]), color=color, lw=2.) ] temp = Arrow(xvec[0] - rin[0], xvec[1] - rin[1], rin[0], rin[1], color=color) h += [temp] temp = Rectangle(t, L, W, color=color, angle=theta) plt.gca().add_artist(temp) h += [temp] elif type == 5: rin = _rot(theta, scipy.array([W + .015, 0])) h += [ plt.plot(xvec[0] + scipy.array([-rin[0], rin[0]]), xvec[1] + scipy.array([-rin[1], rin[1]]), color=color, lw=2.) ] temp = Arrow(xvec[0] - rin[0], xvec[1] - rin[1], rin[0], rin[1], color=color) h += [temp] temp = Rectangle(t, L, W, color=color, angle=theta) plt.gca().add_artist(temp) h += [temp] else: raise ValueError('type out of bounds')
def plot(): from matplotlib.patches import ( Circle, Ellipse, Polygon, Rectangle, Wedge, FancyArrowPatch, ) from matplotlib.collections import PatchCollection from matplotlib.path import Path from matplotlib import pyplot as plt import numpy as np import matplotlib as mpl np.random.seed(123) fig = plt.figure() ax = fig.add_subplot(111) N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) rect = Rectangle(xy=[0.0, 0.25], width=1.0, height=0.5, angle=-45.0) patches.append(rect) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) theta1 = 360.0 * np.random.rand(N) theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((0.3, 0.7), 0.1, 0, 360), # Full circle Wedge((0.7, 0.8), 0.2, 0, 360, width=0.05), # Full ring Wedge((0.8, 0.3), 0.2, 0, 45), # Full sector Wedge((0.8, 0.3), 0.2, 45, 90, width=0.10), # Ring sector ] for _ in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, cmap=mpl.cm.viridis, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) ellipse = Ellipse(xy=[1.0, 0.5], width=1.0, height=0.5, angle=45.0, alpha=0.4) ax.add_patch(ellipse) circle = Circle(xy=[0.0, 1.0], radius=0.5, color="r", alpha=0.4) ax.add_patch(circle) arrow = FancyArrowPatch(posA=[0.25, 0.25], posB=[0.5, 0.25], arrowstyle="->") ax.add_patch(arrow) curved_arrow = FancyArrowPatch( path=Path( [(0.3, 0.3), (0.5, 1.0), (1.0, 0.8), (0.8, 0.3)], [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4], ), arrowstyle="-|>", ) ax.add_patch(curved_arrow) plt.colorbar(p) return fig
dr['df'].append(st) dr['x'].append(mi) dr['xf'].append(st + math.pi / 2) #,ma,st+math.pi/2,mi,f) else: p.append(1) dr['d'].append(ma) dr['df'].append(st + math.pi / 2) dr['x'].append(mi) dr['xf'].append(st) if p != []: print 1 ell1 = Ellipse(xy=(float(lonlat[a][0:7]), float(lonlat[a][8:14])), width=dr['x'][0] / ff, height=dr['d'][0] / ff, angle=dr['xf'][0] / (math.pi / 2 / 180), facecolor='red', alpha=1) #ax.plot([float(lonlat[a][0:7],],[float(lonlat[a][8:14]),]) print 'width', dr['x'][0] / ff else: ell1 = Ellipse(xy=(float(lonlat[a][0:7]), float(lonlat[a][8:14])), width=dr['d'][0] / ff, height=dr['x'][0] / ff, angle=dr['df'][0] / (math.pi / 2 / 180), facecolor='red', alpha=1) #ells = [Ellipse((float(lonlat[a][0:7]), float(lonlat[a][8:14])), int(dr['d'][0])/680, int(dr['x'][0])/680, dr['df'][0]/(math.pi/2/180)) for a in angles] ax.add_patch(ell1)
color='blue', edgecolor='black', hatch='//') ax1.set_xticks([1.5, 2.5, 3.5, 4.5]) bars = ax2.bar(range(1, 5), range(1, 5), color='yellow', ecolor='black') + \ ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5), color='green', ecolor='black') ax2.set_xticks([1.5, 2.5, 3.5, 4.5]) patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.') for bar, pattern in zip(bars, patterns): bar.set_hatch(pattern) ax3.fill([1, 3, 3, 1], [1, 1, 2, 2], fill=False, hatch='\\') ax3.add_patch(Ellipse((4, 1.5), 4, 0.5, fill=False, hatch='*')) ax3.add_patch( Polygon([[0, 0], [4, 1.1], [6, 2.5], [2, 1.4]], closed=True, fill=False, hatch='/')) ax3.set_xlim((0, 6)) ax3.set_ylim((0, 2.5)) # plt.show() from ut_plot import * from os import path run_file = path.basename(__file__) eps_file = path.join(fig_dir, run_file.replace('.py', '.eps')) fig.savefig(eps_file, format='eps', bbox_inches='tight', pad_inches=pad_inches)
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 09:44:08 2021 @author: spunlag """ import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Rectangle plt.figure() plt.axes() ax = plt.gca() ellipse = Ellipse(xy=(0.5, 0.4), width=1, height=0.8, edgecolor='r', fc='r', lw=2) rect = Rectangle((0, 0), 1, 0.8, linewidth=1, edgecolor='k', facecolor='None') ax.add_patch(ellipse) ax.add_patch(rect) ax.plot(0.5, 0.4, 'ko') plt.text(0.3, 0.43, r'($\ell_1 +\bar{r_1}$,$\ell_2 + \bar{r_2}$ )=(0.5,0.4)') ax.plot(1, 0.4, 'ko') plt.text(0.67, 0.35, r'($\ell_1$,$\ell_2 + \bar{r_2}$) = (1,0.4)') ax.plot(0.5, 0.8, 'ko') plt.text(0.35, 0.73, r'($\ell_1 +\bar{r_1}$,$\ell_2$ )=(0.5,0.8)')
s=20, c=y, cmap=cm, marker='o', edgecolors='#202020') clrs = list('rgbmy') for i, (center, cov) in enumerate(zip(centers, covs)): value, vector = sp.linalg.eigh(cov) width, height = value[0], value[1] v = vector[0] / sp.linalg.norm(vector[0]) angle = 180 * np.arctan(v[1] / v[0]) / np.pi e = Ellipse(xy=center, width=width, height=height, angle=angle, color=clrs[i], alpha=0.5, clip_box=ax.bbox) ax.add_artist(e) ax1_min, ax1_max, ax2_min, ax2_max = plt.axis() plt.xlim((x1_min, x1_max)) plt.ylim((x2_min, x2_max)) plt.title('GMM', fontsize=15) plt.grid(b=True, ls=':', color='#606060') # DPGMM dpgmm = BayesianGaussianMixture( n_components=n_components, covariance_type='full',
def detect_fit_ellipse(myimg, y1, y2, zexcl): edgeX = [] edgeY = [] cercle_edge = [] #detect si pas de limbes droits et/ou gauche print() y1, y2 = detect_bord(myimg, axis=1, offset=5) # bords verticaux x1, x2 = detect_bord(myimg, axis=0, offset=5) # bords horizontaux toprint = 'Position X des limbes droit et gauche x1, x2 : ' + str( x1) + ' ' + str(x2) mylog.append(toprint + '\n') print(toprint) iw = myimg.shape[1] TailleX = int(x2 - x1) if TailleX + 10 < int(iw / 5) or TailleX + 10 > int(iw * .99): toprint = 'Pas de limbe solaire pour determiner la geometrie' print(toprint) mylog.append(toprint + '\n') toprint = 'Reprendre les traitements en manuel avec ISIS' print(toprint) mylog.append(toprint + '\n') #print(TailleX, iw) ratio = 0.5 EllipseFit = [0, 0, ratio, 1, 0] section = 0 zone_fit = abs(y2 - y1) ze = int(zexcl * zone_fit) for i in range(y1 + ze, y2 - ze): li = myimg[i, :-5] #li_filter=savgol_filter(li,31,3) li_filter = gaussian_filter1d(li, 11) li_gr = np.gradient(li_filter) #if i==650: #plt.plot(li) #plt.plot(li_gr) #plt.show() a = np.where((abs(li_gr) > 80)) s = a[0] if s.size != 0: c_x1 = s[0] + 10 c_x2 = s[-1] - 10 edgeX.append(c_x1) edgeY.append(i) edgeX.append(c_x2) edgeY.append(i) cercle_edge.append([c_x1, i]) cercle_edge.append([c_x2, i]) zy = np.mean(edgeY) X = np.array(list(zip(edgeX, edgeY))) reg = el.LsqEllipse().fit(X) center, width, height, phi = reg.as_parameters() EllipseFit = [center, width, height, phi] r = height / width section = ((zy - center[1]) / center[1]) print(f'center: {center[0]:.3f}, {center[1]:.3f}') print(f'width: {width*2:.3f}') print(f'height: {height*2:.3f}') print(f'phi: {np.rad2deg(phi):.3f}') print(f'SY/SX ellipse: {r:.3f}') print(f'Section: {section:.3f}') plt.imshow(myimg) #plt.plot(edgeX, edgeY, 'ro', zorder=1) ellipse = Ellipse(xy=center, width=2 * width, height=2 * height, angle=np.rad2deg(phi), edgecolor='b', fc='None', lw=1, label='Fit', zorder=2) # plot cercle sur image np_m = np.asarray(cercle_edge) xm, ym = np_m.T plt.scatter(xm, ym, s=0.1, marker='.', edgecolors=('red')) ax = plt.gca() ax.add_patch(ellipse) plt.show() return EllipseFit, section
def plot_state(mu, sigma, landmarks, map_limits): # Visualizes the state of the kalman filter. # # Displays the mean and standard deviation of the belief, # the state covariance sigma and the position of the # landmarks. # landmark positions lx = [] ly = [] for i in range(len(landmarks)): lx.append(landmarks[i + 1][0]) ly.append(landmarks[i + 1][1]) # mean of belief as current estimate estimated_pose = mu #calculate and plot covariance ellipse covariance = sigma[0:2, 0:2] eigenvals, eigenvecs = np.linalg.eig(covariance) #get largest eigenvalue and eigenvector max_ind = np.argmax(eigenvals) max_eigvec = eigenvecs[:, max_ind] max_eigval = eigenvals[max_ind] #get smallest eigenvalue and eigenvector min_ind = 0 if max_ind == 0: min_ind = 1 min_eigvec = eigenvecs[:, min_ind] min_eigval = eigenvals[min_ind] #chi-square value for sigma confidence interval chisquare_scale = 2.2789 #calculate width and height of confidence ellipse width = 2 * np.sqrt(chisquare_scale * max_eigval) height = 2 * np.sqrt(chisquare_scale * min_eigval) angle = np.arctan2(max_eigvec[1], max_eigvec[0]) #generate covariance ellipse ell = Ellipse(xy=[estimated_pose[0], estimated_pose[1]], width=width, height=height, angle=angle / np.pi * 180) ell.set_alpha(0.25) # plot filter state and covariance plt.clf() plt.gca().add_artist(ell) plt.plot(lx, ly, 'bo', markersize=10) plt.quiver(estimated_pose[0], estimated_pose[1], np.cos(estimated_pose[2]), np.sin(estimated_pose[2]), angles='xy', scale_units='xy') plt.axis(map_limits) plt.pause(0.01)
# add x-tick labels plt.setp(axes, xticks=[y + 1 for y in range(len(comp_data))], xticklabels=plotLabels) #Setup Ellipse Plot NUM = len(msssim) ells = [] B = [] for i in range(0, len(msssim)): B.append([meanComp[i], meanMSSSIM[i]]) W = maxComp[i] - minComp[i] H = (maxMSSSIM[i] - minMSSSIM[i]) print('W, H', W, H) ells.append(Ellipse(xy=B[i], width=W, height=H, angle=0)) fig, ax = plt.subplots(subplot_kw={'aspect': 'auto'}) for q in range(0, len(ells)): e = ells[q] ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) color = np.random.rand(3) if AWS < 4: ax.text(B[q][0], B[q][1], plotLabels[q], style='italic') else: ax.text(B[q][0] + offsetX[q], B[q][1] + offsetY[q], plotLabels[q],
def drawEllipse_full(e_posi, extra_posi, ka, kb, ellipseColor_r='orangered', ellipseColor_t='royalblue', extra_disc_color='orangered', ellipsetransp=0.5): """ This function allows to draw more than one ellipse. The parameter is a list of coordinate (must contain at least two coordinates) The radial and tangential ellipses for the same coordinates are drawn. """ eccentricities = [] for i in range(len(e_posi)): eccentricities0 = distance.euclidean(e_posi[i], (0, 0)) eccentricities.append(eccentricities0) # radial angle_deg = [] for ang in range(len(e_posi)): angle_rad0 = atan2(e_posi[ang][1], e_posi[ang][0]) angle_deg0 = angle_rad0 * 180 / pi angle_deg.append(angle_deg0) my_e = [ Ellipse(xy=e_posi[j], width=eccentricities[j] * ka * 2, height=eccentricities[j] * kb * 2, angle=angle_deg[j]) for j in range(len(e_posi)) ] # tangential angle_deg2 = [] for ang in range(len(e_posi)): angle_rad0_2 = atan2(e_posi[ang][1], e_posi[ang][0]) angle_deg0_2 = angle_rad0_2 * 180 / pi + 90 angle_deg2.append(angle_deg0_2) my_e2 = [ Ellipse(xy=e_posi[j], width=eccentricities[j] * ka * 2, height=eccentricities[j] * kb * 2, angle=angle_deg[j] + 90) for j in range(len(e_posi)) ] fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}, figsize=(4, 3)) for e in my_e: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(ellipsetransp) e.set_facecolor(ellipseColor_r) for e2 in my_e2: ax.add_artist(e2) e2.set_clip_box(ax.bbox) e2.set_alpha(ellipsetransp) e2.set_facecolor(ellipseColor_t) # show the discs on the ellipses-flower for dot in e_posi: plt.plot(dot[0], dot[1], color='k', marker='o', markersize=2) # plt.show() for dot1 in extra_posi: plt.plot(dot1[0], dot1[1], color=extra_disc_color, marker='o', markersize=2) plt.plot(0, 0, color='k', marker='+', markersize=4) # plt.show() # ax.set_xlim([-800, 800]) # ax.set_ylim([-500, 500]) ax.set_xlim([-400, 400]) ax.set_ylim([-260, 260]) # ax.set_title('wS_%s_eS_%s_%s_E.png' %(newWindowSize,ka,kb)) # 边框不可见 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # 坐标不可见 ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) ax.patch.set_facecolor('lightgray') plt.show() fig.savefig('efull%s.svg' % (str(e_posi)[0:15]), bbox_inches='tight', pad_inches=0)
from matplotlib.patches import Ellipse import matplotlib.pyplot as plt plt.figure(1) e = Ellipse(xy=(5, 5), width=10, height=10) plt.plot(e) plt.show()
def drawEllipses_homo(posi, ka, kb, ellipseColor, ellipsetransp=0.5, extra_posi=[], extra_disc_color='orangered'): eccentricities2 = [] for i in range(len(posi)): eccentricities0 = distance.euclidean(posi[i], (0, 0)) eccentricities2.append(eccentricities0) # radial angle_deg3 = [] for ang in range(len(posi)): angle_rad0s = atan2(posi[ang][1], posi[ang][0]) angle_deg0s = angle_rad0s * 180 / pi angle_deg3.append(angle_deg0s) my_e = [ Ellipse(xy=posi[j], width=ka * 2, height=kb * 2, angle=angle_deg3[j]) for j in range(len(posi)) ] fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}, figsize=(4, 3)) for e in my_e: ax.add_artist(e) # random color? e.set_clip_box(ax.bbox) # e.set_alpha(np.random.rand()) e.set_alpha(ellipsetransp) # e.set_facecolor(np.random.rand(3)) # change face color here if ellipseColor == 'orangered': e.set_facecolor('orangered') # 'royalblue' else: e.set_facecolor(ellipseColor) # e.set_facecolor('royalblue') # plot central discs for dot in posi: plt.plot(dot[0], dot[1], color='k', marker='o', markersize=2) if len(extra_posi) != 0: for dot in extra_posi: plt.plot(dot[0], dot[1], color=extra_disc_color, marker='o', markersize=2) plt.plot(0, 0, color='k', marker='+', markersize=4) # set x,y lim ax.set_xlim([-400, 400]) ax.set_ylim([-260, 260]) # 边框不可见 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # 坐标不可见 ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) # set background color ax.patch.set_facecolor('lightgray') plt.show() fig.savefig('e%s.svg' % (str(posi)[0:15]), bbox_inches='tight', pad_inches=0)
def render(self, ctx): """ Render the node. :param ctx: The :class:`_rendering_context` object. """ # Get the axes and default plotting parameters from the rendering # context. ax = ctx.ax() # Resolve the plotting parameters. p = dict(self.plot_params) p["lw"] = _pop_multiple(p, ctx.line_width, "lw", "linewidth") p["ec"] = p["edgecolor"] = _pop_multiple(p, ctx.node_ec, "ec", "edgecolor") p["fc"] = _pop_multiple(p, "none", "fc", "facecolor") fc = p["fc"] p["alpha"] = p.get("alpha", 1) # And the label parameters. if self.label_params is None: l = dict(ctx.label_params) else: l = dict(self.label_params) l["va"] = _pop_multiple(l, "center", "va", "verticalalignment") l["ha"] = _pop_multiple(l, "center", "ha", "horizontalalignment") # Deal with ``fixed`` nodes. scale = self.scale if self.fixed: # MAGIC: These magic numbers should depend on the grid/node units. self.offset[1] += 6 l["va"] = "baseline" l.pop("verticalalignment", None) l.pop("ma", None) if p["fc"] == "none": p["fc"] = "k" diameter = ctx.node_unit * scale if self.aspect is not None: aspect = self.aspect else: aspect = ctx.aspect # Set up an observed node. Note the fc INSANITY. if self.observed: # Update the plotting parameters depending on the style of # observed node. h = float(diameter) w = aspect * float(diameter) if ctx.observed_style == "shaded": p["fc"] = "0.7" elif ctx.observed_style == "outer": h = diameter + 0.1 * diameter w = aspect * diameter + 0.1 * diameter elif ctx.observed_style == "inner": h = diameter - 0.1 * diameter w = aspect * diameter - 0.1 * diameter p["fc"] = fc # Draw the background ellipse. bg = Ellipse(xy=ctx.convert(self.x, self.y), width=w, height=h, **p) ax.add_artist(bg) # Reset the face color. p["fc"] = fc # Draw the foreground ellipse. if ctx.observed_style == "inner" and not self.fixed: p["fc"] = "none" el = Ellipse(xy=ctx.convert(self.x, self.y), width=diameter * aspect, height=diameter, **p) ax.add_artist(el) # Reset the face color. p["fc"] = fc # Annotate the node. ax.annotate(self.content, ctx.convert(self.x, self.y), xycoords="data", xytext=self.offset, textcoords="offset points", **l) return el
def drawEllipse_crowding(e_posi, black_disc_posi, red_disc_posi, crowding_posi, ka, kb, ellipseColor_r='royalblue', savefig=False): """ crowding display: show discs that falls into others crowding zones. """ eccentricities = [] for i in range(len(e_posi)): eccentricities0 = distance.euclidean(e_posi[i], (0, 0)) eccentricities.append(eccentricities0) # radial angle_deg = [] for ang in range(len(e_posi)): angle_rad0 = atan2(e_posi[ang][1], e_posi[ang][0]) angle_deg0 = angle_rad0 * 180 / pi angle_deg.append(angle_deg0) # crowding disc eccentricities_c = [] for i in range(len(crowding_posi)): eccentricities0 = distance.euclidean(crowding_posi[i], (0, 0)) eccentricities_c.append(eccentricities0) angle_deg_c = [] for ang in range(len(crowding_posi)): angle_rad0 = atan2(crowding_posi[ang][1], crowding_posi[ang][0]) angle_deg0 = angle_rad0 * 180 / pi angle_deg_c.append(angle_deg0) my_e = [ Ellipse(xy=crowding_posi[j], width=eccentricities_c[j] * ka * 2, height=eccentricities_c[j] * kb * 2, angle=angle_deg_c[j], linestyle="--") for j in range(len(crowding_posi)) ] fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}, figsize=(8, 6)) for e in my_e: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_edgecolor(ellipseColor_r) e.set_fill(False) # show the discs on the ellipses-flower for dot in e_posi: plt.plot(dot[0], dot[1], color='k', marker='o', markersize=4, alpha=0.3) for dot in black_disc_posi: plt.plot(dot[0], dot[1], color='k', marker='o', markersize=4) for dot in red_disc_posi: plt.plot(dot[0], dot[1], color='orangered', marker='o', markersize=4) # add concentric circles for posi in black_disc_posi: ax.add_patch( plt.Circle((0, 0), distance.euclidean(posi, (0, 0)), alpha=0.5, linestyle="--", fill=False)) # fixation plt.plot(0, 0, color='k', marker='+', markersize=10) # x, y limit ax.set_xlim([-400, 400]) ax.set_ylim([-260, 260]) # 边框不可见 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # 坐标不可见 ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) ax.patch.set_facecolor('lightgray') plt.show() if savefig: fig.savefig('try.svg', bbox_inches='tight', pad_inches=0)
ax1.set_xlabel('Time (ms)') ax1.set_ylabel('Neuron id') ax2.set_xlabel(r'Relative strength of inhibition $g$') ax2.set_ylabel(r'Relative strength of external drive $\eta$') ax3.set_xlabel('Generation') ax3.set_ylabel('Fitness') # raster plot ax1.plot(espikes['times'], espikes['senders'], ls='', marker='.') # search distributions and individuals for mu, sigma in zip(optimization_result['mu_history'], optimization_result['sigma_history']): ellipse = Ellipse( xy=mu, width=2 * sigma[0], height=2 * sigma[1], alpha=0.5, fc='k') ellipse.set_clip_box(ax2.bbox) ax2.add_artist(ellipse) ax2.plot(optimization_result['mu_history'][:, 0], optimization_result['mu_history'][:, 1], marker='.', color='k', alpha=0.5) for generation in optimization_result['pop_history']: ax2.scatter(generation[:, 0], generation[:, 1]) # fitness over generations ax3.errorbar(np.arange(len(optimization_result['fitness_history'])), np.mean(optimization_result['fitness_history'], axis=1), yerr=np.std(optimization_result['fitness_history'], axis=1)) fig.savefig('brunel_alpha_evolution_strategies.pdf')
def draw_frame(df, t, dpi=100, fps=20, display_num=False, display_time=False, show_players=True, highlight_color=None, highlight_player=None, shadow_player=None, text_color='white', flip=False, **anim_args): """ Draws players from time t (in seconds) from a DataFrame df """ fig, ax = draw_pitch(dpi=dpi) dfFrame = get_frame(df, t, fps=fps) if show_players: for pid in dfFrame.index: if pid == 0: #se for bola try: z = dfFrame.loc[pid]['z'] except: z = 0 size = 1.2 + z lw = 0.9 color = 'black' edge = 'white' zorder = 100 else: #se for jogador size = 3 lw = 2 edge = dfFrame.loc[pid]['edgecolor'] if pid == highlight_player: color = highlight_color else: color = dfFrame.loc[pid]['bgcolor'] if dfFrame.loc[pid]['team'] == 'attack': zorder = 21 else: zorder = 20 ax.add_artist( Ellipse((dfFrame.loc[pid]['x'], dfFrame.loc[pid]['y']), size / X_SIZE * 100, size / Y_SIZE * 100, edgecolor=edge, linewidth=lw, facecolor=color, alpha=0.8, zorder=zorder)) try: s = str(int(dfFrame.loc[pid]['player_num'])) except ValueError: s = '' text = plt.text(dfFrame.loc[pid]['x'], dfFrame.loc[pid]['y'], s, horizontalalignment='center', verticalalignment='center', fontsize=8, color=text_color, zorder=22, alpha=0.8) text.set_path_effects([ path_effects.Stroke(linewidth=1, foreground=text_color, alpha=0.8), path_effects.Normal() ]) return fig, ax, dfFrame
def KrigingMapPython(inputPath, namegal, genTable, label='Z', limits=[-3, +2], visualize=False, sizePixelMap=80): #Retrieving galaxy parameters' dictionary #Creating the Kriging maps with Python #reading input file fileKriging = asciidata.open(inputPath + 'gridKrig_' + label + '.txt') xK, yK, zK, errzK = [], [], [], [] maxZmap = 0. minZmap = 0. for jj in range(len(fileKriging[0])): xK.append(fileKriging[0][jj]) yK.append(fileKriging[1][jj]) if fileKriging[2][jj] != 'NA': zK.append(float(fileKriging[2][jj])) errzK.append(float(fileKriging[3][jj])) if float(fileKriging[2][jj]) > maxZmap: maxZmap = float(fileKriging[2][jj]) if float(fileKriging[2][jj]) < minZmap: minZmap = float(fileKriging[2][jj]) else: zK.append(nan) errzK.append(nan) # #reshaping xK = numpy.array(xK).reshape(sizePixelMap, sizePixelMap) yK = numpy.array(yK).reshape(sizePixelMap, sizePixelMap) zK = numpy.array(zK).reshape(sizePixelMap, sizePixelMap) errzK = numpy.array(errzK).reshape(sizePixelMap, sizePixelMap) # minZpoints, maxZpoints = numpy.min(genTable[:, 2]), numpy.max(genTable[:, 2]) rangeZmap = [ numpy.max([numpy.min([minZpoints, minZmap]), limits[0]]), numpy.min([numpy.max([maxZpoints, maxZmap]), limits[1]]) ] # # if savePDF: print "Creating Plot" if visualize: plt.ion() else: plt.ioff() fig = figure(figsize=(6, 5)) clf() ax = subplot(111, aspect='equal') mapp = ax.pcolor(xK, yK, zK, vmin=rangeZmap[0], vmax=rangeZmap[1]) ax.set_xlim([numpy.max(xK[0]), numpy.min(xK[0])]) ax.set_xlabel(r'$\Delta$RA [arcsec]') ax.set_ylim([numpy.min(yK), numpy.max(yK)]) ax.set_ylabel(r'$\Delta$Dec [arcsec]') # Isophotes from matplotlib.patches import Ellipse radiuses = numpy.array([1, 3, 5, 7, 9]) ells = [ Ellipse(xy=[0, 0], width=(2. * jj * Reff[namegal] / numpy.sqrt(b_a[namegal])), height=(2. * jj * Reff[namegal] * numpy.sqrt(b_a[namegal])), angle=90 - PA0[namegal], edgecolor='k', facecolor='none', fill=False, linestyle='dashed') for jj in radiuses ] for ee in ells: ax.add_artist(ee) # #Points ax.scatter(numpy.array(genTable[:, 0]), numpy.array(genTable[:, 1]), c=numpy.array(genTable[:, 2]), vmin=rangeZmap[0], vmax=rangeZmap[1]) # cb = colorbar(mapp) if label == 'Z': cb.set_label('[Z/H] [dex]') elif label == 'CaT': cb.set_label(r'CaT index [$\AA$]') elif label == 'SN': cb.set_label('S/N') elif label == 'sigma': try: cb.set_label(r"$\rm{\sigma}$ [km/s]") except: cb.set_label("Vel dispersion [km/s]") elif label == 'Vel': cb.set_label(r"Vel [km/s]") ax.set_title(namegal) # savefig(inputPath + 'KrigingMap_python_' + label + '.pdf', bbox_edge='tight') print "DONE" # return True
def ResPlot(H,K,L,W,EXP,myrescal,ax,fig): """Plot resolution ellipse for a given scan""" center=N.round(H.shape[0]/2) if center<1: center=0 if center>H.shape[0]: center=H.shape[0] #EXP=[EXP[center]] Style1='' Style2='--' XYAxesPosition=[0.1, 0.6, 0.3, 0.3] XEAxesPosition=[0.1, 0.1, 0.3, 0.3] YEAxesPosition=[0.6, 0.6, 0.3, 0.3] TextAxesPosition=[0.45, 0.0, 0.5, 0.5] GridPoints=101 [R0,RMS]=myrescal.ResMatS(H,K,L,W,EXP) #[xvec,yvec,zvec,sample,rsample]=self.StandardSystem(EXP); myrescal.lattice_calculator.StandardSystem() #print 'shape ',self.lattice_calculator.x.shape qx=myrescal.lattice_calculator.scalar(myrescal.lattice_calculator.x[0,:],myrescal.lattice_calculator.x[1,:],myrescal.lattice_calculator.x[2,:],H,K,L,'latticestar') qy=myrescal.lattice_calculator.scalar(myrescal.lattice_calculator.y[0,:],myrescal.lattice_calculator.y[1,:],myrescal.lattice_calculator.y[2,:],H,K,L,'latticestar') qw=W; #======================================================================================================== #find reciprocal-space directions of X and Y axes o1=myrescal.lattice_calculator.orientation.orient1.T#[:,0] #EXP['orient1'] o2=myrescal.lattice_calculator.orientation.orient2.T#[:,0] #EXP['orient2'] pr=myrescal.lattice_calculator.scalar(o2[0,:],o2[1,:],o2[2,:],myrescal.lattice_calculator.y[0,:],myrescal.lattice_calculator.y[1,:],myrescal.lattice_calculator.y[2,:],'latticestar') o2[0]=myrescal.lattice_calculator.y[0,:]*pr o2[1]=myrescal.lattice_calculator.y[1,:]*pr o2[2]=myrescal.lattice_calculator.y[2,:]*pr if N.abs(o2[0,center])<1e-5: o2[0,center]=0.0 if N.absolute(o2[1,center])<1e-5: o2[1,center]=0.0 if N.absolute(o2[2,center])<1e-5: o2[2,center]=0.0 if N.abs(o1[0,center])<1e-5: o1[0,center]=0.0 if N.absolute(o1[1,center])<1e-5: o1[1,center]=0.0 if N.absolute(o1[2,center])<1e-5: o1[2,center]=0.0 #%======================================================================================================== #%determine the plot range XWidth=max(myrescal.fproject(RMS,0)) YWidth=max(myrescal.fproject(RMS,1)) WWidth=max(myrescal.fproject(RMS,2)) XMax=(max(qx)+XWidth*1.5) XMin=(min(qx)-XWidth*1.5) YMax=(max(qy)+YWidth*1.5) YMin=(min(qy)-YWidth*1.5) WMax=(max(qw)+WWidth*1.5) WMin=(min(qw)-WWidth*1.5) ##fig=pylab.figure() ##%======================================================================================================== ##% plot XY projection proj,sec=myrescal.project(RMS,2) (a,b,c)=N.shape(proj) mat=N.copy(proj) #print 'proj ', proj.shape a1=[];b1=[];theta=[];a1_sec=[];b1_sec=[];theta_sec=[];e=[]; e_sec=[] for i in range(c): matm=N.matrix(mat[:,:,i]) w,v=N.linalg.eig(matm) vm=N.matrix(v) vmt=vm.T mat_diag=vmt*matm*vm a1.append(1.0/N.sqrt(mat_diag[0,0])) b1.append(1.0/N.sqrt(mat_diag[1,1])) thetar=N.arccos(vm[0,0]) theta.append(math.degrees(thetar)) mat_sec=N.copy(sec) #print 'proj ', proj (a,b,c)=N.shape(sec) print 'reached' for i in range(c): rsample='latticestar' ascale=myrescal.lattice_calculator.modvec(o1[0],o1[1],o1[2],rsample)[0] bscale=myrescal.lattice_calculator.modvec(o2[0],o2[1],o2[2],rsample)[0] print 'ascale',ascale print 'bscale',bscale ascale=1 bscale=1 matm_sec=N.matrix(mat_sec[:,:,i]) w_sec,v_sec=N.linalg.eig(matm_sec) vm_sec=N.matrix(v) vmt_sec=vm_sec.T mat_diag_sec=vmt_sec*matm_sec*vm_sec #print 'a',myrescal.lattice_calculator.a[0] a1_sec.append(1.0/N.sqrt(mat_diag_sec[0,0])/ascale) b1_sec.append(1.0/N.sqrt(mat_diag_sec[1,1])/bscale) thetar_sec=N.arccos(vm_sec[0,0]/ascale) theta_sec.append(math.degrees(thetar_sec)) #x0y0=N.array([H[i],K[i]]) x0y0=N.array([qx[i],qy[i]]) print 'a1_sec',a1_sec print 'b1_sec',b1_sec print 'theta_sec',math.degrees(thetar_sec) print 'x0y0',x0y0 #print i,'qx',qx[i] #print 'qy',qy[i] e.append(Ellipse(x0y0,width=2*a1[i],height=2*b1[i],angle=theta[i])) e_sec.append(Ellipse(x0y0,width=2*a1_sec[i],height=2*b1_sec[i],angle=theta_sec[i])) rsample='latticestar' oxmax=XMax/myrescal.lattice_calculator.modvec(o1[0],o1[1],o1[2],rsample) oxmin=XMin/myrescal.lattice_calculator.modvec(o1[0],o1[1],o1[2],rsample) oymax=YMax/myrescal.lattice_calculator.modvec(o2[0],o2[1],o2[2],rsample) oymin=YMin/myrescal.lattice_calculator.modvec(o2[0],o2[1],o2[2],rsample) #make right y-axis #ax2 = fig.add_subplot(2,2,1) #pylab.subplots_adjust(hspace=0.6,wspace=0.3) #ax2.set_ylim(oymin[center], oymax[center]) #ax2.yaxis.tick_right() #ax2.yaxis.set_label_position('right') #ax2.xaxis.set_major_formatter(pylab.NullFormatter()) #ax2.xaxis.set_major_locator(pylab.NullLocator()) #ylabel=r'Q$_y$' +'(units of ['+str(o2[0,center])+' '+str(o2[1,center])+' '+str(o2[2,center])+'])' #ax2.set_ylabel(ylabel) #make top x-axis #if 1: #ax3 = fig.add_axes(ax2.get_position(), frameon=False,label='x-y top') #ax3.xaxis.tick_top() #ax3.xaxis.set_label_position('top') #ax3.set_xlim(oxmin[center], oxmax[center]) #ax3.yaxis.set_major_formatter(NullFormatter()) #ax3.yaxis.set_major_locator(pylab.NullLocator()) #xlabel=r'Q$_x$' +'(units of ['+str(o1[0,center])+' '+str(o1[1,center])+' '+str(o1[2,center])+'])' #ax3.set_xlabel(xlabel) #ax3.set_zorder(2) #make bottom x-axis, left y-axis if 1: #ax = fig.add_axes(ax2.get_position(), frameon=False,label='x-y') #ax.yaxis.tick_left() #ax.yaxis.set_label_position('left') #ax.xaxis.tick_bottom() #ax.xaxis.set_label_position('bottom') for i in range(c): #ax.add_artist(e[i]) e[i].set_clip_box(ax.bbox) e[i].set_alpha(0.5) e[i].set_facecolor('red') ax.add_artist(e_sec[i]) e_sec[i].set_clip_box(ax.bbox) e_sec[i].set_alpha(0.7) e_sec[i].set_facecolor('black')
def venn4(data=None, names=None, fill="number", show_names=True, show_plot=True, axes=None, **kwds): if (data is None) or len(data) != 4: raise Exception("length of data should be 4!") if (names is None) or (len(names) != 4): names = ("set 1", "set 2", "set 3", "set 4") labels = get_labels(data, fill=fill) # set figure size if 'figsize' in kwds and len(kwds['figsize']) == 2: # if 'figsize' is in kwds, and it is a list or tuple with length of 2 figsize = kwds['figsize'] else: # default figure size figsize = (10, 10) # set colors for different Circles or ellipses if 'colors' in kwds and isinstance(kwds['colors'], Iterable) and len(kwds['colors']) >= 4: colors = kwds['colors'] else: colors = ['r', 'g', 'b', 'c'] # draw ellipse, the coordinates are hard coded in the rest of the function patches = [] width, height = 170, 110 # width and height of the ellipses patches.append( Ellipse((170, 170), width, height, -45, color=colors[0], alpha=0.5)) patches.append( Ellipse((200, 200), width, height, -45, color=colors[1], alpha=0.5)) patches.append( Ellipse((200, 200), width, height, -135, color=colors[2], alpha=0.5)) patches.append( Ellipse((230, 170), width, height, -135, color=colors[3], alpha=0.5)) for e in patches: axes.add_patch(e) axes.set_xlim(80, 320) axes.set_ylim(80, 320) axes.set_xticks([]) axes.set_yticks([]) axes.set_aspect("equal") ### draw text # 1 pylab.text(120, 200, labels['1000'], fontsize=10, **alignment) pylab.text(280, 200, labels['0100'], fontsize=10, **alignment) pylab.text(155, 250, labels['0010'], fontsize=10, **alignment) pylab.text(245, 250, labels['0001'], fontsize=10, **alignment) # 2 pylab.text(200, 115, labels['1100'], fontsize=10, **alignment) pylab.text(140, 225, labels['1010'], fontsize=10, **alignment) pylab.text(145, 155, labels['1001'], fontsize=10, **alignment) pylab.text(255, 155, labels['0110'], fontsize=10, **alignment) pylab.text(260, 225, labels['0101'], fontsize=10, **alignment) pylab.text(200, 240, labels['0011'], fontsize=10, **alignment) # 3 pylab.text(235, 205, labels['0111'], fontsize=10, **alignment) pylab.text(165, 205, labels['1011'], fontsize=10, **alignment) pylab.text(225, 135, labels['1101'], fontsize=10, **alignment) pylab.text(175, 135, labels['1110'], fontsize=10, **alignment) # 4 pylab.text(200, 175, labels['1111'], fontsize=10, **alignment) # names of different groups if show_names: pylab.text(110, 110, names[0], fontsize=16, **alignment) pylab.text(290, 110, names[1], fontsize=16, **alignment) pylab.text(130, 275, names[2], fontsize=16, **alignment) pylab.text(270, 275, names[3], fontsize=16, **alignment) #leg_names = [names[0], names[2], names[3], names[1]] ## the legend function messes up the names order so gave it manually here #leg = ax.legend(leg_names, loc='best', fancybox=True) #leg.get_frame().set_alpha(0.5) return axes
def plot_data(self, plot_input=True, plot_fitted=True,plotfile=None, show=None): """Plot the input data overlaid with the ellipse described by the inferred correlated multivariate distribution Parameters ---------- plot_input : bool, default True Whether to plot the input data and their uncertainties plot_fitted : bool, default True Whether to plot the inferred data and their inferred uncertainties plotfile : str, optional Name of a file to write the plot to show : bool, optional, default False Whether to show the plot window """ if not self.fitted: raise RuntimeError("Please run fit() before attempting to plot the results") fitted_data = self.data_summary(printout=False) fitted_mean = fitted_data['mean'].to_numpy().reshape((self.npoints,self.ndim)) print(fitted_mean.shape) fitted_sigma = fitted_data['sd'].to_numpy().reshape((self.npoints,self.ndim)) if self.ndim==np.int(2) and isinstance(self.ndim, int): blue, _, red, *_ = sns.color_palette() f, ax = plt.subplots(1, 1, figsize=(5, 4))#, gridspec_kw=dict(width_ratios=[4, 3])) sns.scatterplot(x=self.data[:,0], y=self.data[:,1]) if plot_input: ax.errorbar(x=self.data[:,0], y=self.data[:,1], xerr=self.sigma[:,0], yerr=self.sigma[:,1],fmt='o',label='input data') if plot_fitted: ax.errorbar(x=fitted_mean[:,0], y=fitted_mean[:,1], xerr=fitted_sigma[:,0], yerr=fitted_sigma[:,1],fmt='o',label='inferred data') mu_post = self.trace.posterior["mu"].mean(axis=(0, 1)).data sigma_post = self.trace.posterior["cov"].mean(axis=(0, 1)).data var_post, U_post = np.linalg.eig(sigma_post) angle_post = 180.0 / np.pi * np.arccos(np.abs(U_post[0, 0])) e_post = Ellipse( mu_post, 2 * np.sqrt(5.991 * var_post[0]), 2 * np.sqrt(5.991 * var_post[1]), angle=angle_post, ) e_post.set_alpha(0.5) e_post.set_facecolor(blue) e_post.set_zorder(10) ax.add_artist(e_post) rect_post = plt.Rectangle((0, 0), 1, 1, fc=blue, alpha=0.5) ax.legend( [rect_post], ["Estimated 95% density region"], loc=2, ) #plt.show() elif self.ndim > 2 and isinstance(int, self.ndim) and np.isfinite(self.ndim): #raise NotImplementedError("This routine doesn't support plotting correlations in more than 2 dimensions yet!") rows = self.ndim - 1 cols = self.ndim - 1 fig = plt.figure() gs = fig.add_gridSpec(rows, cols,left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.05, hspace=0.05) for i in range(self.ndim - 1): for j in range(i+1,self.ndim - 1): ax = fig.add_subplot(gs[i,j]) #plot the data points sns.scatterplot(self.data[:,i], self.data[:,j], ax=ax) if plot_input: ax.errorbar(x=self.data[:,i], y=self.data[:,j], xerr=self.sigma[:,i], yerr=self.sigma[:,j]) if plot_fitted: ax.errorbar(x=fitted_mean[:,i], y=fitted_mean[:,j], xerr=fitted_sigma[:,i], yerr=fitted_sigma[:,j]) mu_post = self.trace.posterior["mu"].mean(axis=(i, j)).data sigma_post = self.trace.posterior["cov"].mean(axis=(i, j)).data var_post, U_post = np.linalg.eig(sigma_post) angle_post = 180.0 / np.pi * np.arccos(np.abs(U_post[0, 0])) e_post = Ellipse( mu_post, 2 * np.sqrt(5.991 * var_post[0]), 2 * np.sqrt(5.991 * var_post[1]), angle=angle_post, ) e_post.set_alpha(0.5) e_post.set_facecolor(blue) e_post.set_zorder(10) ax.add_artist(e_post) else: raise ValueError("Ndim is either less than 2 or is not an integer!") if isinstance(plotfile, str): plt.save(plotfile) elif not show: raise TypeError("plotfile must be a string") if show: plt.show() elif plotfile is not None: plt.close()