Python matplotlib.pyplot.scatter() Examples

The following are 30 code examples for showing how to use matplotlib.pyplot.scatter(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .

Example 1
Project: neural-combinatorial-optimization-rl-tensorflow   Author: MichelDeudon   File: dataset.py    License: MIT License 7 votes vote down vote up
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 2
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 3
Project: OpenTDA   Author: outlace   File: SimplicialComplex.py    License: Apache License 2.0 7 votes vote down vote up
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
Project: OpenTDA   Author: outlace   File: FilteredSimplicialComplex.py    License: Apache License 2.0 7 votes vote down vote up
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 5
Project: MomentumContrast.pytorch   Author: peisuke   File: test.py    License: MIT License 6 votes vote down vote up
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 6
Project: deep-learning-note   Author: wdxtub   File: 3_linear_regression_raw.py    License: MIT License 6 votes vote down vote up
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 7
Project: neural-combinatorial-optimization-rl-tensorflow   Author: MichelDeudon   File: dataset.py    License: MIT License 6 votes vote down vote up
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 8
Project: imgcomp-cvpr   Author: fab-jul   File: plotter.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 9
Project: scanorama   Author: brianhie   File: utils.py    License: MIT License 6 votes vote down vote up
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 10
Project: pymoo   Author: msu-coinlab   File: plotting.py    License: Apache License 2.0 6 votes vote down vote up
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 11
Project: aco-tsp   Author: rochakgupta   File: aco_tsp.py    License: MIT License 6 votes vote down vote up
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 12
Project: prefactor   Author: lofar-astron   File: plot_Ateamclipper.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 13
Project: prefactor   Author: lofar-astron   File: plot_unflagged_fraction.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 14
Project: linguistic-style-transfer   Author: vineetjohn   File: tsne_visualizer.py    License: Apache License 2.0 6 votes vote down vote up
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 15
Project: yatsm   Author: ceholden   File: pixel.py    License: MIT License 6 votes vote down vote up
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 16
Project: yatsm   Author: ceholden   File: pixel.py    License: MIT License 6 votes vote down vote up
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 17
Project: yatsm   Author: ceholden   File: pixel.py    License: MIT License 6 votes vote down vote up
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 18
Project: HRV   Author: pickus91   File: poincare.py    License: MIT License 6 votes vote down vote up
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
Project: OpenTDA   Author: outlace   File: plotting.py    License: Apache License 2.0 6 votes vote down vote up
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 20
Project: miccai-2016-surgical-activity-rec   Author: rdipietro   File: data.py    License: Apache License 2.0 6 votes vote down vote up
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 21
Project: Fundamentals-of-Machine-Learning-with-scikit-learn   Author: PacktPublishing   File: 1logistic_regression.py    License: MIT License 6 votes vote down vote up
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 22
Project: Python-Deep-Learning-SE   Author: ivan-vasilev   File: chapter_06_001.py    License: MIT License 6 votes vote down vote up
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 23
Project: Waymo_Kitti_Adapter   Author: Yao-Shao   File: adapter.py    License: MIT License 6 votes vote down vote up
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 24
Project: LSDMappingTools   Author: LSDtopotools   File: PlottingRaster.py    License: MIT License 6 votes vote down vote up
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
Project: indras_net   Author: gcallah   File: display_methods.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, title, varieties, width, height,
                 anim=True, data_func=None, is_headless=False, legend_pos=4):
        """
        Setup a scatter plot.
        varieties contains the different types of
        entities to show in the plot, which
        will get assigned different colors
        """
        global anim_func

        self.scats = None
        self.anim = anim
        self.data_func = data_func
        self.s = ceil(4096 / width)
        self.headless = is_headless

        fig, ax = plt.subplots()
        ax.set_xlim(0, width)
        ax.set_ylim(0, height)
        self.create_scats(varieties)
        ax.legend(loc = legend_pos)
        ax.set_title(title)
        plt.grid(True)

        if anim and not self.headless:
            anim_func = animation.FuncAnimation(fig,
                                    self.update_plot,
                                    frames=1000,
                                    interval=500,
                                    blit=False) 
Example 26
Project: indras_net   Author: gcallah   File: display_methods.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_scats(self, varieties):
        self.scats = []
        for i, var in enumerate(varieties):
            (x_array, y_array) = self.get_arrays(varieties, var)
            if len(x_array) <= 0:  # no data to graph!
                next
            elif len(x_array) != len(y_array):
                logging.debug("Array length mismatch in scatter plot")
                next
            color = get_color(varieties[var], i)
            scat = plt.scatter(x_array, y_array,
                               c=color, label=var,
                               alpha=1.0, marker="8",
                               edgecolors='none', s=self.s)
            self.scats.append(scat) 
Example 27
Project: fenics-topopt   Author: zfergus   File: triangulate.py    License: MIT License 5 votes vote down vote up
def plot_mesh(V, F, plot_f=False):
    plt.scatter(V[:, 0], V[:, 1])
    if not plot_f:
        return
    for i in range(F.shape[0]):
        vf = V[F[i, :], :]
        plt.plot(vf[:, 0], vf[:, 1]) 
Example 28
Project: deep-learning-note   Author: wdxtub   File: 4_linear_regression_torch.py    License: MIT License 5 votes vote down vote up
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 
Example 29
Project: lirpg   Author: Hwhitetooth   File: results_plotter.py    License: MIT License 5 votes vote down vote up
def plot_curves(xy_list, xaxis, title):
    plt.figure(figsize=(8,2))
    maxx = max(xy[0][-1] for xy in xy_list)
    minx = 0
    for (i, (x, y)) in enumerate(xy_list):
        color = COLORS[i]
        plt.scatter(x, y, s=2)
        x, y_mean = window_func(x, y, EPISODES_WINDOW, np.mean) #So returns average of last EPISODE_WINDOW episodes
        plt.plot(x, y_mean, color=color)
    plt.xlim(minx, maxx)
    plt.title(title)
    plt.xlabel(xaxis)
    plt.ylabel("Episode Rewards")
    plt.tight_layout() 
Example 30
Project: HardRLWithYoutube   Author: MaxSobolMark   File: results_plotter.py    License: MIT License 5 votes vote down vote up
def plot_curves(xy_list, xaxis, title):
    plt.figure(figsize=(8,2))
    maxx = max(xy[0][-1] for xy in xy_list)
    minx = 0
    for (i, (x, y)) in enumerate(xy_list):
        color = COLORS[i]
        plt.scatter(x, y, s=2)
        x, y_mean = window_func(x, y, EPISODES_WINDOW, np.mean) #So returns average of last EPISODE_WINDOW episodes
        plt.plot(x, y_mean, color=color)
    plt.xlim(minx, maxx)
    plt.title(title)
    plt.xlabel(xaxis)
    plt.ylabel("Episode Rewards")
    plt.tight_layout()