本文整理汇总了Python中matplotlib.pyplot.scatter方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.scatter方法的具体用法?Python pyplot.scatter怎么用?Python pyplot.scatter使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.scatter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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()
示例2: generate_dataset
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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 读取数据集
示例3: visualize_2D_trip
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例4: visualize_2D_trip
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例5: plot_ours_mean
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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')
示例6: visualize_cluster
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例7: make_plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例8: plot_3d
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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
示例9: show_landmarks
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
def show_landmarks(image, heatmap, gt_landmarks, gt_heatmap):
"""Show image with pred_landmarks"""
pred_landmarks = []
pred_landmarks, _ = get_preds_fromhm(torch.from_numpy(heatmap).unsqueeze(0))
pred_landmarks = pred_landmarks.squeeze()*4
# pred_landmarks2 = get_preds_fromhm2(heatmap)
heatmap = np.max(gt_heatmap, axis=0)
heatmap = heatmap / np.max(heatmap)
# image = ski_transform.resize(image, (64, 64))*255
image = image.astype(np.uint8)
heatmap = np.max(gt_heatmap, axis=0)
heatmap = ski_transform.resize(heatmap, (image.shape[0], image.shape[1]))
heatmap *= 255
heatmap = heatmap.astype(np.uint8)
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
plt.imshow(image)
plt.scatter(gt_landmarks[:, 0], gt_landmarks[:, 1], s=0.5, marker='.', c='g')
plt.scatter(pred_landmarks[:, 0], pred_landmarks[:, 1], s=0.5, marker='.', c='r')
plt.pause(0.001) # pause a bit so that plots are updated
示例10: plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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()
示例11: main
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例12: main
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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)
示例13: plot_coordinates
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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()
示例14: plot_TS
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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')
示例15: plot_DOY
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import scatter [as 别名]
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')