Python matplotlib.pyplot.scatter() Examples
The following are 30
code examples of matplotlib.pyplot.scatter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: dataset.py From neural-combinatorial-optimization-rl-tensorflow with MIT License | 8 votes |
def visualize_2D_trip(self, trip): plt.figure(figsize=(30,30)) rcParams.update({'font.size': 22}) # Plot cities plt.scatter(trip[:,0], trip[:,1], s=200) # Plot tour tour=np.array(list(range(len(trip))) + [0]) X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--", markersize=100) # Annotate cities with order labels = range(len(trip)) for i, (x, y) in zip(labels,(zip(X,Y))): plt.annotate(i,xy=(x, y)) plt.xlim(0,100) plt.ylim(0,100) plt.show() # Heatmap of permutations (x=cities; y=steps)
Example #2
Source File: SimplicialComplex.py From OpenTDA with Apache License 2.0 | 8 votes |
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]): plt.clf() plt.axis(axes) plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity for i, txt in enumerate(origData): plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels #add lines for edges for edge in [e for e in ripsComplex if len(e)==2]: #print(edge) pt1,pt2 = [origData[pt] for pt in [n for n in edge]] #plt.gca().add_line(plt.Line2D(pt1,pt2)) line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r') plt.gca().add_line(line) #add triangles for triangle in [t for t in ripsComplex if len(t)==3]: pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]] line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None) plt.gca().add_line(line) plt.show()
Example #3
Source File: FilteredSimplicialComplex.py From OpenTDA with Apache License 2.0 | 8 votes |
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]): plt.clf() plt.axis(axes) plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity for i, txt in enumerate(origData): plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels #add lines for edges for edge in [e for e in ripsComplex if len(e)==2]: #print(edge) pt1,pt2 = [origData[pt] for pt in [n for n in edge]] #plt.gca().add_line(plt.Line2D(pt1,pt2)) line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r') plt.gca().add_line(line) #add triangles for triangle in [t for t in ripsComplex if len(t)==3]: pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]] line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None) plt.gca().add_line(line) plt.show()
Example #4
Source File: dataset.py From neural-combinatorial-optimization-rl-tensorflow with MIT License | 7 votes |
def visualize_2D_trip(self,trip,tw_open,tw_close): plt.figure(figsize=(30,30)) rcParams.update({'font.size': 22}) # Plot cities colors = ['red'] # Depot is first city for i in range(len(tw_open)-1): colors.append('blue') plt.scatter(trip[:,0], trip[:,1], color=colors, s=200) # Plot tour tour=np.array(list(range(len(trip))) + [0]) X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--", markersize=100) # Annotate cities with TW tw_open = np.rint(tw_open) tw_close = np.rint(tw_close) time_window = np.concatenate((tw_open,tw_close),axis=1) for tw, (x, y) in zip(time_window,(zip(X,Y))): plt.annotate(tw,xy=(x, y)) plt.xlim(0,60) plt.ylim(0,60) plt.show() # Heatmap of permutations (x=cities; y=steps)
Example #5
Source File: plot_threshold_vs_success_trans.py From pointnet-registration-framework with MIT License | 7 votes |
def make_plot(files, labels): plt.figure() for file_idx in range(len(files)): rot_err, trans_err = read_csv(files[file_idx]) success_dict = count_success(trans_err) x_range = success_dict.keys() x_range.sort() success = [] for i in x_range: success.append(success_dict[i]) success = np.array(success)/total_cases plt.plot(x_range, success, linewidth=3, label=labels[file_idx]) # plt.scatter(x_range, success, s=50) plt.ylabel('Success Ratio', fontsize=40) plt.xlabel('Threshold for Translation Error', fontsize=40) plt.tick_params(labelsize=40, width=3, length=10) plt.grid(True) plt.ylim(0,1.005) plt.yticks(np.arange(0,1.2,0.2)) plt.xticks(np.arange(0,2.1,0.2)) plt.xlim(0,2) plt.legend(fontsize=30, loc=4)
Example #6
Source File: 1logistic_regression.py From Fundamentals-of-Machine-Learning-with-scikit-learn with MIT License | 7 votes |
def show_classification_areas(X, Y, lr): x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) Z = lr.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure(1, figsize=(30, 25)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm) plt.xlabel('X') plt.ylabel('Y') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
Example #7
Source File: plot_Ateamclipper.py From prefactor with GNU General Public License v3.0 | 6 votes |
def main(txtfile = 'Ateamclipper.txt', outfile = 'Ateamclipper.png'): frac_list_xx = [] frac_list_yy = [] freq_list = [] with open(txtfile, 'r') as infile: for line in infile: freq_list.append(float(line.split()[0])) frac_list_xx.append(float(line.split()[1])) frac_list_yy.append(float(line.split()[2])) # Plot the amount of clipped data vs. frequency potentially contaminated by the A-team plt.scatter(numpy.array(freq_list) / 1e6, numpy.array(frac_list_xx), marker = '.', s = 10) plt.xlabel('frequency [MHz]') plt.ylabel('A-team clipping fraction [%]') plt.savefig(outfile) return(0)
Example #8
Source File: 3_linear_regression_raw.py From deep-learning-note with MIT License | 6 votes |
def generate_dataset(true_w, true_b): num_examples = 1000 features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float) # 真实 label labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b # 添加噪声 labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float) # 展示下分布 plt.scatter(features[:, 1].numpy(), labels.numpy(), 1) plt.show() return features, labels # batch 读取数据集
Example #9
Source File: plotter.py From imgcomp-cvpr with GNU General Public License v3.0 | 6 votes |
def plot_ours_mean(measures_readers, metric, color, show_ids): if not show_ids: show_ids = [] ops = [] for first, measures_reader in flag_first_iter(measures_readers): this_op_bpps = [] this_op_values = [] for img_name, bpp, value in measures_reader.iter_metric(metric): this_op_bpps.append(bpp) this_op_values.append(value) ours_mean_bpp, ours_mean_value = np.mean(this_op_bpps), np.mean(this_op_values) ops.append((ours_mean_bpp, ours_mean_value)) plt.scatter(ours_mean_bpp, ours_mean_value, marker='x', zorder=10, color=color, label='Ours' if first else None) for (bpp, value), job_id in zip(sorted(ops), show_ids): plt.annotate(job_id, (bpp + 0.04, value), horizontalalignment='bottom', verticalalignment='center')
Example #10
Source File: utils.py From scanorama with MIT License | 6 votes |
def visualize_cluster(coords, cluster, cluster_labels, cluster_name=None, size=1, viz_prefix='vc', image_suffix='.svg'): if not cluster_name: cluster_name = cluster labels = [ 1 if c_i == cluster else 0 for c_i in cluster_labels ] c_idx = [ i for i in range(len(labels)) if labels[i] == 1 ] nc_idx = [ i for i in range(len(labels)) if labels[i] == 0 ] colors = np.array([ '#cccccc', '#377eb8' ]) image_fname = '{}_cluster{}{}'.format( viz_prefix, cluster, image_suffix ) plt.figure() plt.scatter(coords[nc_idx, 0], coords[nc_idx, 1], c=colors[0], s=size) plt.scatter(coords[c_idx, 0], coords[c_idx, 1], c=colors[1], s=size) plt.title(str(cluster_name)) plt.savefig(image_fname, dpi=500)
Example #11
Source File: chapter_06_001.py From Python-Deep-Learning-SE with MIT License | 6 votes |
def plot_latent_distribution(encoder, x_test, y_test, batch_size=128): """ Display a 2D plot of the digit classes in the latent space. We are interested only in z, so we only need the encoder here. :param encoder: the encoder network :param x_test: test images :param y_test: test labels :param batch_size: size of the mini-batch """ z_mean, _, _ = encoder.predict(x_test, batch_size=batch_size) plt.figure(figsize=(6, 6)) markers = ('o', 'x', '^', '<', '>', '*', 'h', 'H', 'D', 'd', 'P', 'X', '8', 's', 'p') for i in np.unique(y_test): plt.scatter(z_mean[y_test == i, 0], z_mean[y_test == i, 1], marker=MarkerStyle(markers[i], fillstyle='none'), edgecolors='black') plt.xlabel("z[0]") plt.ylabel("z[1]") plt.show()
Example #12
Source File: adapter.py From Waymo_Kitti_Adapter with MIT License | 6 votes |
def plot_points_on_image(self, projected_points, camera_image, rgba_func, point_size=5.0): """Plots points on a camera image. Args: projected_points: [N, 3] numpy array. The inner dims are [camera_x, camera_y, range]. camera_image: jpeg encoded camera image. rgba_func: a function that generates a color from a range value. point_size: the point size. """ self.plot_image(camera_image) xs = [] ys = [] colors = [] for point in projected_points: xs.append(point[0]) # width, col ys.append(point[1]) # height, row colors.append(rgba_func(point[2])) plt.scatter(xs, ys, c=colors, s=point_size, edgecolors="none")
Example #13
Source File: test.py From MomentumContrast.pytorch with MIT License | 6 votes |
def show(mnist, targets, ret): target_ids = range(len(set(targets))) colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'violet', 'orange', 'purple'] plt.figure(figsize=(12, 10)) ax = plt.subplot(aspect='equal') for label in set(targets): idx = np.where(np.array(targets) == label)[0] plt.scatter(ret[idx, 0], ret[idx, 1], c=colors[label], label=label) for i in range(0, len(targets), 250): img = (mnist[i][0] * 0.3081 + 0.1307).numpy()[0] img = OffsetImage(img, cmap=plt.cm.gray_r, zoom=0.5) ax.add_artist(AnnotationBbox(img, ret[i])) plt.legend() plt.show()
Example #14
Source File: plotting.py From pymoo with Apache License 2.0 | 6 votes |
def plot_3d(*args, no_fill=False, labels=None, **kwargs): fig = plt.figure() from mpl_toolkits.mplot3d import Axes3D ax = fig.add_subplot(111, projection='3d') for i, F in enumerate(args): if no_fill: kwargs["s"] = 20 kwargs["marker"] = '.' kwargs["facecolors"] = (0, 0, 0, 0) kwargs["edgecolors"] = 'r' if labels: ax.scatter(F[:, 0], F[:, 1], F[:, 2], label=labels[i], **kwargs) else: ax.scatter(F[:, 0], F[:, 1], F[:, 2], **kwargs) return ax
Example #15
Source File: data.py From miccai-2016-surgical-activity-rec with Apache License 2.0 | 6 votes |
def plot_label_seq(label_seq, num_classes, y_value): """ Plot a label sequence. The sequence will be shown using a horizontal colored line, with colors corresponding to classes. Args: label_seq: An int NumPy array with shape `[duration, 1]`. num_classes: An integer. y_value: A float. The y value at which the horizontal line will sit. """ label_seq = label_seq.flatten() x = np.arange(0, label_seq.size) y = y_value*np.ones(label_seq.size) plt.scatter(x, y, c=label_seq, marker='|', lw=2, vmin=0, vmax=num_classes)
Example #16
Source File: aco_tsp.py From aco-tsp with MIT License | 6 votes |
def plot(self, line_width=1, point_radius=math.sqrt(2.0), annotation_size=8, dpi=120, save=True, name=None): x = [self.nodes[i][0] for i in self.global_best_tour] x.append(x[0]) y = [self.nodes[i][1] for i in self.global_best_tour] y.append(y[0]) plt.plot(x, y, linewidth=line_width) plt.scatter(x, y, s=math.pi * (point_radius ** 2.0)) plt.title(self.mode) for i in self.global_best_tour: plt.annotate(self.labels[i], self.nodes[i], size=annotation_size) if save: if name is None: name = '{0}.png'.format(self.mode) plt.savefig(name, dpi=dpi) plt.show() plt.gcf().clear()
Example #17
Source File: plotting.py From OpenTDA with Apache License 2.0 | 6 votes |
def drawComplex(data, ph, axes=[-6, 8, -6, 6]): plt.clf() plt.axis(axes) # axes = [x1, x2, y1, y2] plt.scatter(data[:, 0], data[:, 1]) # plotting just for clarity for i, txt in enumerate(data): plt.annotate(i, (data[i][0] + 0.05, data[i][1])) # add labels # add lines for edges for edge in [e for e in ph.ripsComplex if len(e) == 2]: # print(edge) pt1, pt2 = [data[pt] for pt in [n for n in edge]] # plt.gca().add_line(plt.Line2D(pt1,pt2)) line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r') plt.gca().add_line(line) # add triangles for triangle in [t for t in ph.ripsComplex if len(t) == 3]: pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]] line = plt.Polygon([pt1, pt2, pt3], closed=False, color="blue", alpha=0.3, fill=True, edgecolor=None) plt.gca().add_line(line) plt.show()
Example #18
Source File: poincare.py From HRV with MIT License | 6 votes |
def plotPoincare(RRints): """ Input : - RRints: [list] of RR intervals Output : - Poincare plot """ ax1 = RRints[:-1] ax2 = RRints[1:] plt.scatter(ax1, ax2, c = 'r', s = 12) plt.xlabel('RR_n (s)') plt.ylabel('RR_n+1 (s)') plt.show()
Example #19
Source File: pixel.py From yatsm with MIT License | 6 votes |
def plot_VAL(dates, y, mpl_cmap, reps=2): """ Create a "Valerie Pasquarella" plot (repeated DOY plot) Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot mpl_cmap (colormap): matplotlib colormap reps (int, optional): number of additional repetitions """ doy = np.array([d.timetuple().tm_yday for d in dates]) year = np.array([d.year for d in dates]) # Replicate `reps` times _doy = doy.copy() for r in range(1, reps + 1): _doy = np.concatenate((_doy, doy + r * 366)) _year = np.tile(year, reps + 1) _y = np.tile(y, reps + 1) sp = plt.scatter(_doy, _y, c=_year, cmap=mpl_cmap, marker='o', edgecolors='none', s=35) plt.colorbar(sp) plt.xlabel('Day of Year')
Example #20
Source File: pixel.py From yatsm with MIT License | 6 votes |
def plot_DOY(dates, y, mpl_cmap): """ Create a DOY plot Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot mpl_cmap (colormap): matplotlib colormap """ doy = np.array([d.timetuple().tm_yday for d in dates]) year = np.array([d.year for d in dates]) sp = plt.scatter(doy, y, c=year, cmap=mpl_cmap, marker='o', edgecolors='none', s=35) plt.colorbar(sp) months = mpl.dates.MonthLocator() # every month months_fmrt = mpl.dates.DateFormatter('%b') plt.tick_params(axis='x', which='minor', direction='in', pad=-10) plt.axes().xaxis.set_minor_locator(months) plt.axes().xaxis.set_minor_formatter(months_fmrt) plt.xlim(1, 366) plt.xlabel('Day of Year')
Example #21
Source File: pixel.py From yatsm with MIT License | 6 votes |
def plot_TS(dates, y, seasons): """ Create a standard timeseries plot Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot seasons (bool): Plot seasonal symbology """ # Plot data if seasons: months = np.array([d.month for d in dates]) for season_months, color, alpha in SEASONS.values(): season_idx = np.in1d(months, season_months) plt.plot(dates[season_idx], y[season_idx], marker='o', mec=color, mfc=color, alpha=alpha, ls='') else: plt.scatter(dates, y, c='k', marker='o', edgecolors='none', s=35) plt.xlabel('Date')
Example #22
Source File: tsne_visualizer.py From linguistic-style-transfer with Apache License 2.0 | 6 votes |
def plot_coordinates(coordinates, plot_path, markers, label_names, fig_num): matplotlib.use('svg') import matplotlib.pyplot as plt plt.figure(fig_num) for i in range(len(markers) - 1): plt.scatter(x=coordinates[markers[i]:markers[i + 1], 0], y=coordinates[markers[i]:markers[i + 1], 1], marker=plot_markers[i % len(plot_markers)], c=colors[i % len(colors)], label=label_names[i], alpha=0.75) plt.legend(loc='upper right', fontsize='x-large') plt.axis('off') plt.savefig(fname=plot_path, format="svg", bbox_inches='tight', transparent=True) plt.close()
Example #23
Source File: plot_unflagged_fraction.py From prefactor with GNU General Public License v3.0 | 6 votes |
def main(ms_list, frac_list, outfile='unflagged_fraction.png'): ms_list = input2strlist_nomapfile(ms_list) frac_list = input2strlist_nomapfile(frac_list) frac_list = np.array([float(f) for f in frac_list]) outdir = os.path.dirname(outfile) if not os.path.exists(outdir): os.makedirs(outdir) # Get frequencies freq_list = [] for ms in ms_list: # open the main table and print some info about the MS t = pt.table(ms, readonly=True, ack=False) tfreq = pt.table(t.getkeyword('SPECTRAL_WINDOW'),readonly=True,ack=False) ref_freq = tfreq.getcol('REF_FREQUENCY',nrow=1)[0] freq_list.append(ref_freq) freq_list = np.array(freq_list) / 1e6 # MHz # Plot the unflagged fraction vs. frequency plt.scatter(freq_list, frac_list) plt.xlabel('frequency [MHz]') plt.ylabel('unflagged fraction') plt.savefig(outfile)
Example #24
Source File: PlottingRaster.py From LSDMappingTools with MIT License | 6 votes |
def SetCustomExtent(self,xmin,xmax,ymin,ymax): """ This function sets the plot extent in map coordinates and remakes the axis ticks Args: xmin: the minimum extent in easting xmax: the maximum extent in easting ymin: the minimum extent in northing ymax: the maximum extent in northing Author: MDH """ # Get the tick properties self._xmin = xmin self._ymin = ymin self._xmax = xmax self._ymax = ymax self.make_ticks() # Annoying but the scatter plot resets the extents so you need to reassert them self.ax_list[0].set_xlim(self._xmin,self._xmax) self.ax_list[0].set_ylim(self._ymin,self._ymax) self.ax_list = self.make_base_image(self.ax_list)
Example #25
Source File: logistic_regression_reg.py From PRML with MIT License | 5 votes |
def plotData(X, y): # positiveクラスのデータのインデックス positive = [i for i in range(len(y)) if y[i] == 1] # negativeクラスのデータのインデックス negative = [i for i in range(len(y)) if y[i] == 0] plt.scatter(X[positive, 0], X[positive, 1], c='red', marker='o', label="positive") plt.scatter(X[negative, 0], X[negative, 1], c='blue', marker='o', label="negative")
Example #26
Source File: linear_regression.py From PRML with MIT License | 5 votes |
def plotData(X, y): plt.scatter(X, y, c='red', marker='o', label="Training data") plt.xlabel("Population of city in 10,000s") plt.ylabel("Profit in $10,000s") plt.xlim(4, 24) plt.ylim(-5, 25)
Example #27
Source File: logistic_regression.py From PRML with MIT License | 5 votes |
def plotData(X, y): # positiveクラスのデータのインデックス positive = [i for i in range(len(y)) if y[i] == 1] # negativeクラスのデータのインデックス negative = [i for i in range(len(y)) if y[i] == 0] plt.scatter(X[positive, 0], X[positive, 1], c='red', marker='o', label="positive") plt.scatter(X[negative, 0], X[negative, 1], c='blue', marker='o', label="negative")
Example #28
Source File: argva_node_clustering.py From pytorch_geometric with MIT License | 5 votes |
def plot_points(colors): model.eval() z = model.encode(data.x, data.train_pos_edge_index) z = TSNE(n_components=2).fit_transform(z.cpu().numpy()) y = data.y.cpu().numpy() plt.figure(figsize=(8, 8)) for i in range(dataset.num_classes): plt.scatter(z[y == i, 0], z[y == i, 1], s=20, color=colors[i]) plt.axis('off') plt.show()
Example #29
Source File: RealSenseVideo.py From laplacian-meshes with GNU General Public License v3.0 | 5 votes |
def getFrame(foldername, index, loadColor = True, plotFrame = False): depthFile = "%s/B-depth-float%i.png"%(foldername, index) xyFile = "%s/B-cloud%i.png"%(foldername, index) Z = imreadf(depthFile) XYZ = imreadf(xyFile) X = XYZ[:, 0:-1:3] Y = XYZ[:, 1:-1:3] uvname = "%s/B-depth-uv%i.png"%(foldername, index) u = np.zeros(Z.shape) v = np.zeros(Z.shape) C = 0.5*np.ones((Z.shape[0], Z.shape[1], 3)) #Default gray loadedColor = False if loadColor and os.path.exists(uvname): uv = imreadf(uvname) u = uv[:, 0::2] v = uv[:, 1::2] C = scipy.misc.imread("%s/B-color%i.png"%(foldername, index)) / 255.0 loadedColor = True if plotFrame: x = X[Z > 0] y = Y[Z > 0] z = Z[Z > 0] c = getColorsFromMap(u, v, C, Z > 0) fig = plt.figure() #ax = Axes3D(fig) plt.scatter(x, y, 30, c) plt.show() return [X, Y, Z, C, u, v, loadedColor]
Example #30
Source File: logistic_regression_cg.py From PRML with MIT License | 5 votes |
def plotData(X, y): # positiveクラスのデータのインデックス positive = [i for i in range(len(y)) if y[i] == 1] # negativeクラスのデータのインデックス negative = [i for i in range(len(y)) if y[i] == 0] plt.scatter(X[positive, 0], X[positive, 1], c='red', marker='o', label="positive") plt.scatter(X[negative, 0], X[negative, 1], c='blue', marker='o', label="negative")