def printField(self, testcase=0, rnd=0, showplot=0, radius=0): """ Plot field Args: pic_id (int): Save image id showplot (bool): Show plot graph """ x_cm, y_cm, x_ch, y_ch, i = [], [], [], [], 0 for node in self.getNodes(): if node.getType() == 'CH': x_ch.append(node.getX()) y_ch.append(node.getY()) elif node.getType() != 'BS': x_cm.append(node.getX()) y_cm.append(node.getY()) plt.scatter([-50], [50], s=35, label='BS', marker=mark.MarkerStyle('o', fillstyle='full')) plt.scatter(x_cm, y_cm, s=18, label='CM', marker=mark.MarkerStyle('.', fillstyle='full')) plt.scatter(x_ch, y_ch, s=20, label='CH', marker=mark.MarkerStyle(',', fillstyle='full')) plt.gca().add_patch(patches.Rectangle((0, 0), self.getWidth(), self.getHeight(), linewidth='1', linestyle='-', facecolor='none', edgecolor='k')) plt.xlabel('X') plt.ylabel('Y') plt.title("Field") plt.legend(loc=0) if rnd: plt.savefig(config.root + "/R%02d/T%02d/%04d/%04d" % (self.getRadius(), (self.__t * 100), testcase, rnd), dpi=72) if showplot: plt.show() plt.clf()
def test_deprecated_marker(): with pytest.warns(MatplotlibDeprecationWarning): ms = markers.MarkerStyle() markers.MarkerStyle(ms) # No warning on copy. with pytest.warns(MatplotlibDeprecationWarning): ms = markers.MarkerStyle(None) markers.MarkerStyle(ms) # No warning on copy.
def analyst(t_init, size): start_time = time.time() try: data = xl.load_workbook(config.root + "/R%02d/R%02dT%02ddata.xls" % (size, size, t_init)) except Exception as err: print(err) return T_case = [] SOP_case = [] Size_case = [] for sheet in data.worksheets: SOP_case.append(sheet.max_row - 1) Size_case.append(np.mean(sheet['C'][1:], dtype=np.float64)) T_case.append(np.mean(sheet['D'][1:], dtype=np.float64)) T_avg = np.mean(T_case, dtype=np.float64) if T_case else 0 Size_avg = np.mean(Size_case, dtype=np.float64) if Size_case else 0 SOP_avg = np.mean(SOP_case, dtype=np.float64) if SOP_case else 0 '''T by size''' plt.plot([1, len(T_case) + 1], [T_avg, T_avg], label='T avg = %.4f' % T_avg) plt.scatter(list(range(1, len(T_case) + 1)), T_case, s=10, marker=mark.MarkerStyle('x', fillstyle='full'), color='red') plt.xlabel('Testcase') plt.ylabel('T') plt.title("T avg R=%02d T=%.2f" % (size, t_init / 100)) plt.legend(loc=0) #plt.show() plt.savefig(config.root + "/R%02d/R%02dT%02d_T_avg" % (size, size, t_init), dpi=300) plt.clf() ''' Cluster Size avg by size ''' plt.plot([1, len(Size_case) + 1], [Size_avg, Size_avg], label='Cluster Size avg = %.4f' % Size_avg) plt.scatter(list(range(1, len(Size_case) + 1)), Size_case, s=10, marker=mark.MarkerStyle('x', fillstyle='full'), color='red') plt.xlabel('Testcase') plt.ylabel('Cluster size') plt.title("Cluster size avg R=%02d T=%.2f" % (size, t_init / 100)) plt.legend(loc=0) #plt.show() plt.savefig(config.root + "/R%02d/R%02dT%02d_Size_avg" % (size, size, t_init), dpi=300) plt.clf() ''' SOP by size ''' plt.plot([1, len(SOP_case) + 1], [SOP_avg, SOP_avg], label='SOP avg = %.4f' % SOP_avg) plt.scatter(list(range(1, len(SOP_case) + 1)), SOP_case, s=10, marker=mark.MarkerStyle('x', fillstyle='full'), color='red') plt.xlabel('Testcase') plt.ylabel('Round') plt.title("SOP avg R=%02d T=%.2f" % (size, t_init / 100)) plt.legend(loc=0) #plt.show() plt.savefig(config.root + "/R%02d/R%02dT%02d_SOP_avg" % (size, size, t_init), dpi=300) plt.clf() print("Processing analyst which set initial radius at {} and initial T valuse at {} finished within time {}s.\nRunning on processer {}\n".format(size, t_init, time.time() - start_time, mp.current_process())) del data
def set_markers(): paths = [] for marker in markers: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed(marker_obj.get_transform()) paths.append(path) scatter_plot.set_paths(paths)
def mscatter(x,y,ax=None, m=None, **kw): ''' Scatter function that accepts list of markers and list of sizes in addition to list of colors Example: N = 40 x, y, c = np.random.rand(3, N) s = np.random.randint(10, 220, size=N) m = np.repeat(["o", "s", "D", "*"], N/4) fig, ax = plt.subplots() scatter = mscatter(x, y, c=c, s=s, m=m, ax=ax) plt.show() from https://stackoverflow.com/questions/52303660/iterating-markers-in-plots/52303895#52303895 ''' import matplotlib.markers as mmarkers if not ax: ax=plt.gca() sc = ax.scatter(x,y,**kw) if (m is not None) and (len(m)==len(x)): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) return sc
def fit(self, data): if self.centroids == {}: for i in range(self.num_clusters): self.centroids[i] = data[i] for i in range(self.epochs): self.classifications = {} for cluster in range(self.num_clusters): self.classifications[cluster] = [] for features in data: distances = [np.linalg.norm(features - self.centroids[centroid]) for centroid in self.centroids] classification = distances.index(min(distances)) self.classifications[classification].append(features) prev_centroid = dict(self.centroids) for classification in self.classifications: self.centroids[classification] = np.mean(self.classifications[classification], axis=0) optimized = True color = {0: "blue", 1: "green", 2: "red"} for cent in self.centroids: original_centroid = prev_centroid[cent] current_centroid = self.centroids.get(cent) if np.sum((original_centroid - current_centroid) / original_centroid * 100) > self.tolerance: optimized = False if self.epochs == 1 or self.epochs == 2: plt.scatter(current_centroid[0], current_centroid[1], color=color.get(cent), facecolors=color.get(cent), marker=mmarkers.MarkerStyle(marker='o', fillstyle='none'), edgecolors=color.get(cent)) plt.savefig("task3_iter{}_b.jpg".format(self.epochs)) if optimized: break
def render(self): print("render---------->") # Create figure and axes fig, ax = plt.subplots(1, 5, figsize=(30, 6)) # Display the image ax[0].imshow(self.sand, cmap='gray', vmin=0, vmax=1) # Create a Rectangle patch rect = patches.Rectangle((self.pos.x - int(self.crop_size / 2), self.pos.y - int(self.crop_size / 2)), self.crop_size, self.crop_size, linewidth=1, edgecolor='r', facecolor='none') # Add the patch to the Axes ax[0].add_patch(rect) ax[0].set_title("x=%d,y=%d,angle=%d" % (self.pos.x, self.pos.y, self.angle)) marker = mmarkers.MarkerStyle(marker="$ \\rightarrow$") marker._transform = marker.get_transform().rotate_deg(self.angle) ax[0].scatter(self.pos.x, self.pos.y, s=50, c='red', marker=marker) self.get_state(ax).cpu().numpy() plt.show()
def VisualisePCA_2D(finalDf, targets, chartTitle): # initialize plot with labels fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(1, 1, 1) ax.set_xlabel('Principal Component 1', fontsize=15) ax.set_ylabel('Principal Component 2', fontsize=15) ax.set_title(chartTitle, fontsize=20) # initialize marker colors and type colors = ['r', 'g', 'b', 'k'] mark_chars = ['.', 'v', 's', '*', 'H'] markers = [] # create marker objects based on characters in mark_chars for c in mark_chars: markers.append(mrk.MarkerStyle(marker=c)) # counter for target count = 0 # for each target, plot on grid for target in targets: indicesToKeep = finalDf['target'] == target ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1'], finalDf.loc[indicesToKeep, 'principal component 2'], c=colors[count % len(colors)], marker=markers[count % len(markers)], s=100) count += 1 ax.legend(targets) ax.grid() fig.show()
def scatter_optimum(): alphas = sd.distinct('lr') baselines = sd.distinct('baseline') layers = sd.distinct('n_hid_lay') lay_cols = sd.get_col_list(layers) get = db.prepare('SELECT dropout, test_err FROM opts INNER JOIN ' 'optimum ON optimum.path = opts.path AND ' '( opts.arch = $1 AND opts.baseline = $2 ' 'AND opts.n_hid_lay = $3 AND opts.lr = $4)') fig = plt.figure() ax = fig.add_subplot(111) legend = OrderedDict() for alpha, col in lay_cols.items(): # label = 'LR:' + lt_str(alpha) legend[alpha] = mlines.Line2D([], [], color=col, marker=None, linewidth=15, label=str(alpha)) for symb, arch in [('o', 'LSTM'), ('*', 'GRU')]: mmarkers.MarkerStyle(symb) legend[arch] = mlines.Line2D([], [], color='k', marker=symb, linestyle=None, markersize=15, label=arch) for alpha, col in get_col_list(alphas).items(): # col = [int(c * 255) for c in col] for baseline in baselines: for hid_lay in layers: x, y = list(), list() res = get(arch, baseline, hid_lay, alpha) # res = [it[:-2] for it in tmp # if it[-1] == alpha] if res: do, te = tuple(zip(*res)) i = np.array(te).argmin() x.append(alpha) # do[i]) y.append(te[i]) ax.scatter(x, y, marker=symb, alpha=.5, facecolors=[lay_cols[hid_lay]] * len(x), s=(np.log2(float(baseline)) - np.log2(64)) * 200) ax.set_ylim([1.1, 1.5]) ax.legend(handles=list(legend.values())) ax.get_xaxis().set_ticks(alphas) ax.get_xaxis().set_ticklabels([lt_str(a) for a in alphas]) plt.show()
def scatter_auto_mark(x, y, c, ax=None, m=("|", "_"), fillstyle="none", **kw): """ TODO:Quick hack, can be generalised further :param x: :param y: :param c: :param ax: :param m: :param kw: :return: @param fillstyle: """ import matplotlib.markers as mmarkers if not ax: ax = pyplot.gca() sc = ax.scatter(x, y, c=c, **kw) if m is not None and len(m) == len(x): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker, fillstyle=fillstyle) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) elif (c is not None and isinstance(c[0], (int, numpy.ndarray)) and len(c) == len(x)): # TODO: HANDLE numpy ndarray # better paths = [] for c_ in c: if isinstance(c_, numpy.ndarray): c_ = c_.item() if isinstance(m[c_], mmarkers.MarkerStyle): marker_obj = m[c_] else: marker_obj = mmarkers.MarkerStyle(m[c_], fillstyle=fillstyle) paths.append(marker_obj.get_path().transformed( marker_obj.get_transform())) sc.set_paths(paths) else: pass # raise NotImplemented return sc
def _update_2d_graph(self, num): x_updated = np.hstack((self.pos_gt.x[:num + 1].tolist(), self.pos_pred.x[:num + 1].tolist())) y_updated = np.hstack((self.pos_gt.y[:num + 1].tolist(), self.pos_pred.y[:num + 1].tolist())) paths_gt = [] paths_ped = [] for i in range(num + 1): marker_gt = mmarkers.MarkerStyle('o') marker_ped = mmarkers.MarkerStyle('x') path_gt = marker_gt.get_path().transformed(marker_gt.get_transform()) path_ped = marker_ped.get_path().transformed(marker_ped.get_transform()) paths_gt.append(path_gt) paths_ped.append(path_ped) self.graph._paths = np.concatenate([paths_gt, paths_ped]) self.graph.set_facecolors(np.concatenate([self.colors[:num + 1], self.colors[:num + 1]])) self.graph.set_edgecolors(np.concatenate([self.colors[:num + 1], self.colors[:num + 1]])) self.graph.set_offsets(np.hstack((y_updated[:, np.newaxis], x_updated[:, np.newaxis])))
def get_state(self, ax=None): print("get_state--------->") resize = T.Compose([ T.ToPILImage(), T.Resize(self.state_dim[0], interpolation=Image.CUBIC), T.ToTensor() ]) img = Image.open(self.filename).convert('L') # If we directly crop and rotate the image, we may loose information # from the edges. Hence we do the following: # * Crop a larger portion of image # * Rotate it to make the cropped image in the direction # of car's orientation # * Then crop it to required size crop_img = utilityImage.center_crop_img(img, self.pos.x, self.pos.y, self.crop_size * 3) if ax is not None: utilityImage.show_img(ax[1], crop_img, "large crop") print(" large crop-------->") r_img = utilityImage.rotate_img(crop_img, -self.angle) if ax is not None: utilityImage.show_img(ax[2], r_img, "rotated crop") print(" rotated crop-------->") r_img_x, r_img_y = r_img.size crop_img = utilityImage.center_crop_img(r_img, int(r_img_x / 2), int(r_img_y / 2), self.crop_size) if ax is not None: utilityImage.show_img(ax[3], crop_img, "final crop") print(" final crop-------->") np_img = np.asarray(crop_img) / 255 np_img = np_img.astype(int) screen = np.ascontiguousarray(np_img, dtype=np.float32) screen = torch.from_numpy(screen) screen = resize(screen) if ax is not None: print("crop get state-------->") np_img = screen.squeeze(0).numpy() np_img = np_img.astype(int) ax[4].imshow(np_img, cmap='gray', vmin=0, vmax=1) marker = mmarkers.MarkerStyle(marker="$ \\rightarrow$") ax[4].scatter(self.state_dim[0] / 2, self.state_dim[1] / 2, s=100, c='red', marker=marker) ax[4].set_title("final resized img") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("crop------end") return screen.to(device)
def update(params, indices, cache): if parametric: out = callable_else_value_no_cast(x, param_excluder(params)) if not isinstance(out, tuple): out = np.asanyarray(out).T x_, y_ = out else: x_, y_ = eval_xy(x, y, param_excluder(params), cache) scatter.set_offsets(np.column_stack([x_, y_])) c_ = check_callable_xy(c, x_, y_, param_excluder(params), cache) s_ = check_callable_xy(s, x_, y_, param_excluder(params, "s"), cache) ec_ = check_callable_xy(edgecolors, x_, y_, param_excluder(params), cache) fc_ = check_callable_xy(facecolors, x_, y_, param_excluder(params), cache) a_ = check_callable_alpha(alpha, param_excluder(params, "alpha"), cache) marker_ = callable_else_value_no_cast(marker, param_excluder(params), cache) if marker_ is not None: if not isinstance(marker_, mmarkers.MarkerStyle): marker_ = mmarkers.MarkerStyle(marker_) path = marker_.get_path().transformed(marker_.get_transform()) scatter.set_paths((path, )) if c_ is not None: try: c_ = to_rgba_array(c_) except ValueError as array_err: try: c_ = scatter.cmap(c_) except TypeError as cmap_err: raise ValueError( "If c is a function it must return either an RGB(A) array" "or a 1D array of valid color names or values to be colormapped" ) scatter.set_facecolor(c_) if ec_ is not None: scatter.set_edgecolor(ec_) if fc_ is not None: scatter.set_facecolor(c_) if s_ is not None: if isinstance(s_, Number): s_ = np.broadcast_to(s_, (len(x_), )) scatter.set_sizes(s_) if a_ is not None: scatter.set_alpha(a_) update_datalim_from_bbox(ax, scatter.get_datalim(ax.transData), stretch_x=stretch_x, stretch_y=stretch_y) ax.autoscale_view()
def change_scatter_markers(cls, sc, markers): paths = [] for marker in markers: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths)
def align_marker(marker, halign='center', valign='middle', fillstyle='full'): """ create markers with specified alignment. Parameters ---------- marker : a valid marker specification. See mpl.markers halign : string, float {'left', 'center', 'right'} Specifies the horizontal alignment of the marker. *float* values specify the alignment in units of the markersize/2 (0 is 'center', -1 is 'right', 1 is 'left'). valign : string, float {'top', 'middle', 'bottom'} Specifies the vertical alignment of the marker. *float* values specify the alignment in units of the markersize/2 (0 is 'middle', -1 is 'top', 1 is 'bottom'). Returns ------- marker_array : numpy.ndarray A Nx2 array that specifies the marker path relative to the plot target point at (0, 0). Notes ----- The mark_array can be passed directly to ax.plot and ax.scatter, e.g.:: ax.plot(1, 1, marker=align_marker('>', 'left')) """ if isinstance(halign, str): halign = { 'right': -1., 'middle': 0., 'center': 0., 'left': 1., }[halign] if isinstance(valign, str): valign = { 'top': -1., 'middle': 0., 'center': 0., 'bottom': 1., }[valign] # Define the base marker bm = markers.MarkerStyle(marker, fillstyle=fillstyle) # Get the marker path and apply the marker transform to get the # actual marker vertices (they should all be in a unit-square # centered at (0, 0)) m_arr = bm.get_path().transformed(bm.get_transform()).vertices # Shift the marker vertices for the specified alignment. m_arr[:, 0] += halign / 2 m_arr[:, 1] += valign / 2 return Path(m_arr, bm.get_path().codes)
def _update_3d_graph(self, num): # num is zero-index --> set to num+1 x_updated = np.concatenate([self.pos_gt.x[:num+1].tolist(), self.pos_pred.x[:num+1].tolist()]) y_updated = np.concatenate([self.pos_gt.y[:num+1].tolist(), self.pos_pred.y[:num+1].tolist()]) z_updated = np.concatenate([self.pos_gt.z[:num+1].tolist(), self.pos_pred.z[:num+1].tolist()]) paths_gt = [] paths_ped = [] for i in range(num+1): marker_gt = mmarkers.MarkerStyle('o') marker_ped = mmarkers.MarkerStyle('x') path_gt = marker_gt.get_path().transformed(marker_gt.get_transform()) path_ped = marker_ped.get_path().transformed(marker_ped.get_transform()) paths_gt.append(path_gt) paths_ped.append(path_ped) self.graph._paths = np.concatenate([paths_gt, paths_ped]) self.graph._facecolor3d = np.concatenate([self.colors[:num+1], self.colors[:num+1]]) self.graph._edgecolor3d = np.concatenate([self.colors[:num+1], self.colors[:num+1]]) self.graph._offsets3d = (x_updated, y_updated, z_updated)
def plot_data(data, data2, colors, colors2): x = [d['x'] for d in data] y = [d['y'] for d in data] c = [colors[d['class']] for d in data] plt.scatter(x, y, c=c) xc = [d['x'] for d in data2] yc = [d['y'] for d in data2] cc = [colors2[d['class']] for d in data2] plt.scatter(xc, yc, c=cc, marker=mrk.MarkerStyle("+")) plt.show()
def get_state(self, ax=None): distance = self.pos.distance(self.target) / self.max_distance goal_vector = self.target - self.pos goal_vector = Vector(goal_vector.x, self.max_y - goal_vector.y) velocity = Vector(2, 0).rotate(self.angle) orientation = Vector(*velocity).angle(goal_vector) / 180. resize = T.Compose([ T.ToPILImage(), T.Resize(self.state_dim[0], interpolation=Image.CUBIC), T.ToTensor() ]) img = Image.open(self.filename).convert('L') # If we directly crop and rotate the image, we may loose information # from the edges. Hence we do the following: # * Crop a larger portion of image # * Rotate it to make the cropped image in the direction # of car's orientation # * Then crop it to required size crop_img = imgutils.center_crop_img(img, self.pos.x, self.pos.y, self.crop_size * 3) if ax is not None: show_img(ax[1], crop_img, "large crop") r_img = imgutils.rotate_img(crop_img, -self.angle) if ax is not None: show_img(ax[2], r_img, "rotated crop") r_img_x, r_img_y = r_img.size crop_img = imgutils.center_crop_img(r_img, int(r_img_x / 2), int(r_img_y / 2), self.crop_size) if ax is not None: show_img(ax[3], crop_img, "final crop") np_img = np.asarray(crop_img) / 255 np_img = np_img.astype(int) screen = np.ascontiguousarray(np_img, dtype=np.float32) screen = torch.from_numpy(screen) screen = resize(screen) if ax is not None: np_img = screen.squeeze(0).numpy() np_img = np_img.astype(int) ax[4].imshow(np_img, cmap='gray', vmin=0, vmax=1) marker = mmarkers.MarkerStyle(marker="$ \\rightarrow$") ax[4].scatter(self.state_dim[0] / 2, self.state_dim[0] / 2, s=100, c='red', marker=marker) ax[4].set_title("final resized img") return screen, torch.Tensor([distance, orientation, -orientation])
def part1_2_and_3(epochs): """ Does the task subparts 1,2, and 3 :param epochs: Number of iterations to run Kmeans """ classifier = KMeans_custom(epochs=epochs, centroids={0: [6.2, 3.2], 1: [6.6, 3.7], 2: [6.5, 3.0]}) classifier.fit(X) for cent in classifier.centroids: plt.scatter(classifier.centroids[cent][0], classifier.centroids[cent][1], marker=mmarkers.MarkerStyle(marker='o', fillstyle='full'), color="b", s=150, linewidths=5, facecolors=[1, 1, 1], edgecolors="black", alpha=0.5) for classification in classifier.classifications: color = colors[classification] for feature in classifier.classifications[classification]: plt.scatter(feature[0], feature[1], marker=mmarkers.MarkerStyle(marker='^', fillstyle='full'), color=color, s=150, linewidths=5, facecolors=color, edgecolors=color, alpha=0.5) print(classifier.classifications) print(classifier.centroids) plt.savefig("task3_iter{}_a.jpg".format(epochs))
def new_scatter(self, *args, **kwargs): colors = kwargs.get("c", None) co2mk = kwargs.pop("co2mk",None) FinalCollection = old_scatter(self, *args, **kwargs) if co2mk is not None and isinstance(colors, np.ndarray): Color2Marker = GetColor2Marker(co2mk) paths=[] for col in colors: mk=Color2Marker[tuple(col)] marker_obj = mmarkers.MarkerStyle(mk) paths.append(marker_obj.get_path().transformed( marker_obj.get_transform())) FinalCollection.set_paths(paths) return FinalCollection
def mscatter(x, y, ax=None, m=None, **kw): import matplotlib.markers as mmarkers sc = ax.scatter(x, y, **kw) if (m is not None) and (len(m) == len(x)): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path( ) #.transformed(marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) return sc
def _mscatter(x, y, markers=None, ax=None, **kwargs): # based on https://stackoverflow.com/questions/52303660/iterating-markers-in-plots/52303895#52303895 sc = ax.scatter(x, y, **kwargs) if markers is not None: paths = [] for marker in markers: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) return sc
def scatter_rotation(x, y, rotation_degrees, marker=None, ax=None, vertical=False, **kwargs): """ Scatter plot with points rotated by rotation_degrees clockwise. Parameters ---------- x, y : array-like or scalar. Commonly, these parameters are 1D arrays. rotation_degrees: array-like or scalar, default None. Rotates the marker in degrees, clockwise. 0 degrees is facing the direction of play. In a horizontal pitch, 0 degrees is this way → marker: MarkerStyle, optional The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. Defaults to None, in which case it takes the value of rcParams["scatter.marker"] (default: 'o') = 'o'. ax : matplotlib.axes.Axes, default None The axis to plot on. vertical : bool, default False Rotates the markers correctly for the orientation. If using a vertical setup where the x and y axis are flipped set vertical=True. **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.scatter. Returns ------- paths : matplotlib.collections.PathCollection """ rotation_degrees = np.ma.ravel(rotation_degrees) if x.size != rotation_degrees.size: raise ValueError("x and rotation_degrees must be the same size") # rotated counter clockwise - this makes it clockwise with zero facing the direction of play rotation_degrees = -rotation_degrees # if horizontal rotate by 90 degrees so 0 degrees is this way → if vertical is False: rotation_degrees = rotation_degrees - 90 markers = [] for degrees in rotation_degrees: marker_style = mmarkers.MarkerStyle(marker=marker) marker_style._transform = marker_style.get_transform().rotate_deg( degrees) markers.append(marker_style) rotated_scatter = _mscatter(x, y, markers=markers, ax=ax, **kwargs) return rotated_scatter
def mscatter(self, x, y, ax=None, m=None, **kwargs): import matplotlib.markers as mmarkers if not ax: ax = plt.gca() scs = ax.scatter(x, y, **kwargs) if (m is not None): # and (len(m)==len(x)): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) scs.set_paths(paths) return scs
def test_ball_path(): y = 15 x = 0 omega = 0. noise = [1, 1] v0 = 100. ball = BallPath(x0=x, y0=y, omega_deg=omega, velocity=v0, noise=noise) dt = 1 f1 = KalmanFilter(dim_x=6, dim_z=2) dt = 1 / 30. # time step ay = -.5 * dt**2 f1.F = np.mat([ [1, dt, 0, 0, 0, 0], # x=x0+dx*dt [0, 1, dt, 0, 0, 0], # dx = dx [0, 0, 0, 0, 0, 0], # ddx = 0 [0, 0, 0, 1, dt, ay], # y = y0 +dy*dt+1/2*g*dt^2 [0, 0, 0, 0, 1, dt], # dy = dy0 + ddy*dt [0, 0, 0, 0, 0, 1] ]) # ddy = -g f1.H = np.mat([[1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) f1.R = np.eye(2) * 5 f1.Q = np.eye(6) * 0. omega = radians(omega) vx = cos(omega) * v0 vy = sin(omega) * v0 f1.x = np.mat([x, vx, 0, y, vy, -9.8]).T f1.P = np.eye(6) * 500. z = np.mat([[0, 0]]).T count = 0 markers.MarkerStyle(fillstyle='none') np.set_printoptions(precision=4) while f1.x[3, 0] > 0: count += 1 #f1.update (z) f1.predict() plt.scatter(f1.x[0, 0], f1.x[3, 0], color='green')
def __init__(self, root): super().__init__(root) self.root = root self.root.title('CsvDataAnalyzer') self.color_list = clr.cnames self.marker_list = mkr.MarkerStyle().markers self.equal_list = ['OFF', 'ON'] self.hist_kde_list = ['OFF', 'ON'] self.dict_data_frame = {} self.selected_data = [] self.created_figure = [] self.init_menu() self.init_combo_box() self.init_status_bar() self.init_data_list() self.init_data_set_button() self.init_entry_box()
def align_marker( marker, halign='center', valign='middle', ): # Define the base marker bm = markers.MarkerStyle(marker) # Get the marker path and apply the marker transform to get the # actual marker vertices (they should all be in a unit-square # centered at (0, 0)) m_arr = bm.get_path().transformed(bm.get_transform()).vertices # Shift the marker vertices for the specified alignment. m_arr[:, 0] += halign / 2 m_arr[:, 1] += valign / 2 return Path(m_arr, bm.get_path().codes)
def mscatter(x, y, ax=None, m=None, **kwargs): # https://stackoverflow.com/questions/52303660/iterating-markers-in-plots/52303895#52303895 import matplotlib.markers as mmarkers if not ax: ax = plt.gca() sc = ax.scatter(x, y, **kwargs) if (m is not None) and (len(m) == len(x)): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) return sc
def _create_path_collection(self): # load default marker from rcParams if self._markerstyle is None: self._markerstyle = mpl.rcParams['scatter.marker'] if self._markerobj is None: if isinstance(self._markerstyle, mmarkers.MarkerStyle): self._markerobj = self._markerstyle else: self._markerobj = mmarkers.MarkerStyle(self._markerstyle) self.markerpath = self._markerobj.get_path().transformed( self._markerobj.get_transform()) if not self._markerobj.is_filled(): self._edgecolors = 'face' if self._edgecolors is None: self.edgecolors = 'face' if self._linewidths is None: self._linewidths = mpl.rcParams['lines.linewidth']
def mscatter(xy, ax, m, c, alpha, title): import matplotlib.markers as mmarkers if not ax: ax = plt.gca() sc = ax.scatter(xy[:, 0], xy[:, 1], c=c, alpha=alpha) if (m is not None) and (len(m) == len(xy)): paths = [] for marker in m: if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed( marker_obj.get_transform()) paths.append(path) sc.set_paths(paths) if not title is None: ax.set_title(title, fontsize=40) ax.axis('equal') ax.set_xticks([], []) ax.set_yticks([], []) return sc