本文整理汇总了Python中matplotlib.pyplot.scatter函数的典型用法代码示例。如果您正苦于以下问题:Python scatter函数的具体用法?Python scatter怎么用?Python scatter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了scatter函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: altitude
def altitude():
global alt, i
#we want to create temporary file to parse, so that we don't mess with the nmea.txt file
f1 = open('temp.txt', 'w') #creates and opens a writable txt file
f1.truncate() #erase contents of file
shutil.copyfile('nmea.txt', 'temp.txt') #copy nmea.txt to temp.txt
f1.close() #close writable file
f1 = open('temp.txt', 'r') #open and read only
try: #best to use try/finally so that the file opens and closes correctly
for line in f1: #read each line in temp.txt
if(line[4] == 'G'): # fifth character in $GPGGA
if(len(line) > 50): # when there is a lock, the sentence gets filled with data
#print line
gpgga = nmea.GPGGA()
gpgga.parse(line)
alt = gpgga.antenna_altitude
i +=1 #increment the counter
print i
print alt
plt.scatter(x=[i], y=[float(alt)], s = 1, c='r') #plot each point
finally:
f1.close()
i=0
#axis is autoscaled
plt.ylabel('meters')
plt.xlabel('counts')
plt.title('ALTITUDE')
plt.show()
示例2: work
def work(self):
self.worked = True
kwargs = dict(
weights=self.weights,
mus=self.mus,
sigmas=self.sigmas,
low=self.low,
high=self.high,
q=self.q,
)
samples = GMM1(rng=self.rng,
size=(self.n_samples,),
**kwargs)
samples = np.sort(samples)
edges = samples[::self.samples_per_bin]
#print samples
pdf = np.exp(GMM1_lpdf(edges[:-1], **kwargs))
dx = edges[1:] - edges[:-1]
y = 1 / dx / len(dx)
if self.show:
plt.scatter(edges[:-1], y)
plt.plot(edges[:-1], pdf)
plt.show()
err = (pdf - y) ** 2
print np.max(err)
print np.mean(err)
print np.median(err)
if not self.show:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
示例3: plot_2d_simple
def plot_2d_simple(data,y=None):
if y==None:
plt.scatter(data[:,0],data[:,1],s=50)
else:
nY=len(y)
Ycol=[collist[ y.astype(int)[i] -1 % len(collist)] for i in xrange(nY)]
plt.scatter(data[:,0],data[:,1],c=Ycol,s=40 )
示例4: tuning
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
"""
Plot a tuning curve
"""
if smooth is not None:
xs, ys = smoothfit(x, y, smooth)
plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
else:
ys = asarray([0])
if pal is None:
pal = sns.color_palette("husl", n_colors=len(x) + 6)
pal = pal[2 : 2 + len(x)][::-1]
plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
if err is not None:
plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
plt.xlabel("Wall distance (mm)")
plt.ylabel(ylabel)
plt.xlim([-2.5, 32.5])
errTmp = err
errTmp[isnan(err)] = 0
rng = max([nanmax(ys), nanmax(y + errTmp)])
plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
plt.yticks(linspace(0, rng, 3))
plt.xticks(range(0, 40, 10))
sns.despine()
return rng
示例5: draw
def draw(data, classes, model, resolution=100):
mycm = mpl.cm.get_cmap('Paired')
one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
np.arange(two_min, two_max, (two_max-two_min)/resolution))
inputs = np.c_[xx1.ravel(), xx2.ravel()]
z = []
for i in range(len(inputs)):
z.append(predict(model, inputs[i])[0])
result = np.array(z).reshape(xx1.shape)
plt.contourf(xx1, xx2, result, cmap=mycm)
plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
t = np.zeros(15)
for i in range(15):
if i < 5:
t[i] = 0
elif i < 10:
t[i] = 1
else:
t[i] = 2
plt.scatter(model[:, 0], model[:, 1], s=150, c=t, cmap=mycm)
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.show()
示例6: plot_dpi_dpr_distribution
def plot_dpi_dpr_distribution(args, dpis, dprs, diagnoses):
print log.INFO, 'Plotting estimate distributions...'
diagnoses = np.array(diagnoses)
diagnoses[(0.25 <= diagnoses) & (diagnoses <= 0.75)] = 0.5
# Setup plot
fig, ax = plt.subplots()
pt.setup_axes(plt, ax)
biomarkers_str = args.method if args.biomarkers is None else ', '.join(args.biomarkers)
ax.set_title('DP estimation using {0} at {1}'.format(biomarkers_str, ', '.join(args.visits)))
ax.set_xlabel('DP')
ax.set_ylabel('DPR')
plt.scatter(dpis, dprs, c=diagnoses, edgecolor='none', s=25.0,
vmin=0.0, vmax=1.0, cmap=pt.progression_cmap,
alpha=0.5)
# Plot legend
# noinspection PyUnresolvedReferences
rects = [mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_cn + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_mci + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_ad + (0.5,), linewidth=0)]
labels = ['CN', 'MCI', 'AD']
legend = ax.legend(rects, labels, fontsize=10, ncol=len(rects), loc='upper center', framealpha=0.9)
legend.get_frame().set_edgecolor((0.6, 0.6, 0.6))
# Draw or save the plot
plt.tight_layout()
if args.plot_file is not None:
plt.savefig(args.plot_file, transparent=True)
else:
plt.show()
plt.close(fig)
示例7: plot
def plot(i, pcanc, lr, pp, labelFlag, Y):
if len(str(i)) == 1:
fig = plt.figure(i)
else:
fig = plt.subplot(i)
if pcanc == 0:
plt.title(
' learning_rate: ' + str(lr)
+ ' perplexity: ' + str(pp))
print("Plotting tSNE")
else:
plt.title(
'PCA-n_components: ' + str(pcanc)
+ ' learning_rate: ' + str(lr)
+ ' perplexity: ' + str(pp))
print("Plotting PCA-tSNE")
plt.scatter(Y[:, 0], Y[:, 1], c=colors)
if labelFlag == 1:
for label, cx, cy in zip(y, Y[:, 0], Y[:, 1]):
plt.annotate(
label.decode('utf-8'),
xy = (cx, cy),
xytext = (-10, 10),
fontproperties=font,
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.9))
#arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
print("Done.")
示例8: plot_data
def plot_data(models,dataframe,flag = 0):
"""need good and bad models, plots all the data"""
if flag == 0:
for key in models[0]:
g=dataframe[(dataframe['module_category']==key[0]) & \
(dataframe['component_category']==key[1])]
plt.scatter(g['time'],g['number_repair'],c =np.random.rand(3,1))
plt.xlabel("Time")
plt.ylabel("number of repairs")
plt.title("%s, and %s" %(key[0], key[1]))
plt.show()
if flag ==1:
for key in models[1]:
g=dataframe[(dataframe['module_category']==key[0]) & \
(dataframe['component_category']==key[1])]
plt.scatter(g['time'],g['number_repair'],c =np.random.rand(3,1))
plt.xlabel("Time")
plt.ylabel("number of repairs")
if models[1][key] == [1,1,1]:
plt.title("too little data: %s, and %s" %(key[0],key[1]))
else:
plt.title("no curve fit: %s, and %s" %(key[0], key[1]))
plt.show()
示例9: visualizeEigenvalues
def visualizeEigenvalues(eVal, verboseLevel):
real = []
imag = []
for z in eVal:
rp = z.real
im = z.imag
if not (rp == np.inf or rp == - np.inf) \
and not (im == np.inf or im == - np.inf):
real.append(rp)
imag.append(im)
if verboseLevel>=1:
print("length of regular real values=" + str(len(real)))
print("length of regular imag values=" + str(len(imag)))
print("minimal real part=" + str(min(real)), "& maximal real part=" + str(max(real)))
print("minimal imag part=" + str(min(imag)), "& maximal imag part=" + str(max(imag)))
if verboseLevel==2:
print("all real values:", str(real))
print("all imag values:", str(imag))
# plt.scatter(real[4:],img[4:])
plt.scatter(real, imag)
plt.grid(True)
plt.xlabel("realpart")
plt.ylabel("imagpart")
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
示例10: export
def export(self, query, n_topics, n_words, title="PCA Export", fname="PCAExport"):
vec = DictVectorizer()
rows = topics_to_vectorspace(self.model, n_topics, n_words)
X = vec.fit_transform(rows)
pca = skPCA(n_components=2)
X_pca = pca.fit(X.toarray()).transform(X.toarray())
match = []
for i in range(n_topics):
topic = [t[1] for t in self.model.show_topic(i, len(self.dictionary.keys()))]
m = None
for word in topic:
if word in query:
match.append(word)
break
pyplot.figure()
for i in range(X_pca.shape[0]):
pyplot.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)
pyplot.text(X_pca[i, 0], X_pca[i, 1], s=' '.join([str(i), match[i]]))
pyplot.title(title)
pyplot.savefig(fname)
pyplot.close()
示例11: scatter
def scatter(frame, var1, var2, var3=None, reg=False, **args):
import matplotlib.cm as cm
if type(frame) is copper.Dataset:
frame = frame.frame
x = frame[var1]
y = frame[var2]
if var3 is None:
plt.scatter(x.values, y.values, **args)
else:
options = list(set(frame[var3]))
for i, option in enumerate(options):
f = frame[frame[var3] == option]
x = f[var1]
y = f[var2]
c = cm.jet(i/len(options),1)
plt.scatter(x, y, c=c, label=option, **args)
plt.legend()
if reg:
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
line = slope * x + intercept # regression line
plt.plot(x, line, c='r')
plt.xlabel(var1)
plt.ylabel(var2)
示例12: plot_contour_with_labels
def plot_contour_with_labels(contour, frame_index=0):
"""
Makes a beautiful plot with all the points labeled.
Parameters:
One frame's worth of a contour
"""
contour_x = contour[:, 0, frame_index]
contour_y = contour[:, 1, frame_index]
plt.plot(contour_x, contour_y, 'r', lw=3)
plt.scatter(contour_x, contour_y, s=35)
labels = list(str(l) for l in range(0, len(contour_x)))
for label_index, (label, x, y), in enumerate(
zip(labels, contour_x, contour_y)):
# Orient the label for the first half of the points in one direction
# and the other half in the other
if label_index <= len(contour_x) // 2 - \
1: # Minus one since indexing
xytext = (20, -20) # is 0-based
else:
xytext = (-20, 20)
plt.annotate(
label, xy=(
x, y), xytext=xytext, textcoords='offset points', ha='right', va='bottom', bbox=dict(
boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(
arrowstyle='->', connectionstyle='arc3,rad=0')) # , xytext=(0,0))
示例13: kmeans
def kmeans(points, k):
centroids = random.sample(points, k)
allColors = list(colors.cnames.keys())
iterations = 0
oldCentroids = None
while not shouldStop(oldCentroids, centroids, iterations):
oldCentroids = centroids
iterations += 1
#we need numpy arrays to do some cool linalg stuff
points = np.array(points)
centroids = np.array(centroids)
labels = getLabels(points, centroids)
centroids = getCentroids(points, labels, k)
#plotting centroids as a red star
x, y = zip(*centroids)
plt.scatter(x,y, marker = '*', color = 'r', s = 80)
#life is a coloring book so lets put colors on stuff
counter = 0
for centroid in labels.keys():
for point in labels[centroid]:
plt.scatter(point[0], point[1], color = allColors[counter])
#6 was chosen to avoid white, white is apparantly some multiple of 5
counter += 6
print (iterations)
return centroids
示例14: plotscatterdate
def plotscatterdate(x,y):
plt.scatter(x,y)
plt.xlim(0,)
plt.xlabel('Number of Railways')
plt.ylabel('Price in Pounds')
plt.title('Scatter of Price against Number of Railways')
plt.show()
示例15: plot_words
def plot_words (V,labels=None,color='b',mark='o',fa='bottom'):
W = tsne(V,2)
i = 0
plt.scatter(W[:,0], W[:,1],c=color,marker=mark,s=50.0)
for label,x,y in zip(labels, W[:,0], W[:,1]):
plt.annotate(label.decode('utf8'), xy=(x,y), xytext=(-1,1), textcoords='offset points', ha= 'center', va=fa, bbox=dict(boxstyle='round,pad=0.1', fc='white', alpha=0))
i += 1