本文整理汇总了Python中matplotlib.pyplot.subplot函数的典型用法代码示例。如果您正苦于以下问题:Python subplot函数的具体用法?Python subplot怎么用?Python subplot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了subplot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_tripcolor
def test_tripcolor():
x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75])
y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75])
triangles = np.asarray([
[0, 1, 3], [1, 4, 3],
[1, 2, 4], [2, 5, 4],
[3, 4, 6], [4, 7, 6],
[4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]])
# Triangulation with same number of points and triangles.
triang = mtri.Triangulation(x, y, triangles)
Cpoints = x + 0.5*y
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
Cfaces = 0.5*xmid + ymid
plt.subplot(121)
plt.tripcolor(triang, Cpoints, edgecolors='k')
plt.title('point colors')
plt.subplot(122)
plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')
plt.title('facecolors')
示例2: plot_feature_comparison
def plot_feature_comparison(title, trajectory, features):
plotCount = features.shape[1]
pointCount = features.shape[0]
fig = plt.figure()
plt.title(title)
#plt.ion()
#plt.show()
max = np.amax(features)
min = np.amin(features)
print "min=" + str(min) + ", max=" + str(max)
for i in range(plotCount):
plt.subplot(plotCount/2, 2, 1+i)
f = features[:,i]
for k in range(pointCount):
color = ''
if(f[k] > max * 0.6):
color = 'r'
elif(f[k] > max * 0.3):
color = 'y'
elif(f[k] < min * 0.3):
color = 'b'
elif(f[k] < min * 0.6):
color = 'g'
if (color != ''):
plt.plot(trajectory[k,0], trajectory[k,1], color+'.', markersize=20)
#plt.draw()
plt.plot(trajectory[:,0], trajectory[:,1], 'k')
plt.show()
#raw_input()
return
示例3: plot_data
def plot_data(kx,omega,F,F_R,F_L,K,O):
#plt.figure(4)
#plt.imshow(K,extent=[omega[0],omega[-1],kx[0],kx[-1]],\
# interpolation = "nearest", aspect = "auto")
#plt.xlabel('KX')
#plt.colorbar()
#plt.figure(5)
#plt.imshow(O,extent =[omega[0],omega[-1],kx[0],kx[-1]],interpolation="nearest", aspect="auto")
#plt.xlabel('omega')
#plt.colorbar()
plt.figure(6)
pylab.subplot(1,2,1)
plt.imshow(abs(F_R), extent= [omega[0],omega[-1],kx[0],kx[-1]], interpolation= "nearest", aspect = "auto")
plt.xlabel('abs FFT_R')
plt.colorbar()
plt.subplot(1,2,2)
plt.imshow(abs(F_L), extent= [omega[0],omega[-1],kx[0],kx[-1]], interpolation= "nearest", aspect = "auto")
plt.xlabel('abs FFT_L')
plt.colorbar()
plt.figure(7)
plt.subplot(2,1,1)
plt.imshow(abs(F_L+F_R),extent=[omega[0],omega[-1],kx[0],kx[-1]],interpolation= "nearest", aspect = "auto")
plt.xlabel('abs(F_L+F_R) reconstructed')
plt.colorbar()
pylab.subplot(2,1,2)
plt.imshow(abs(F),extent=[omega[0],omega[-1],kx[0],kx[-1]],interpolation ="nearest",aspect = "auto")
plt.xlabel('FFT of the original data')
plt.colorbar()
#plt.show()
return
示例4: plot_images
def plot_images(data_list, data_shape="auto", fig_shape="auto"):
"""
plotting data on current plt object.
In default,data_shape and fig_shape are auto.
It means considered the data as a sqare structure.
"""
n_data = len(data_list)
if data_shape == "auto":
sqr = int(n_data ** 0.5)
if sqr * sqr != n_data:
data_shape = (sqr + 1, sqr + 1)
else:
data_shape = (sqr, sqr)
plt.figure(figsize=data_shape)
for i, data in enumerate(data_list):
plt.subplot(data_shape[0], data_shape[1], i + 1)
plt.gray()
if fig_shape == "auto":
fig_size = int(len(data) ** 0.5)
if fig_size ** 2 != len(data):
fig_shape = (fig_size + 1, fig_size + 1)
else:
fig_shape = (fig_size, fig_size)
Z = data.reshape(fig_shape[0], fig_shape[1])
plt.imshow(Z, interpolation="nearest")
plt.tick_params(labelleft="off", labelbottom="off")
plt.tick_params(axis="both", which="both", left="off", bottom="off", right="off", top="off")
plt.subplots_adjust(hspace=0.05)
plt.subplots_adjust(wspace=0.05)
示例5: test_clipping
def test_clipping():
exterior = mpath.Path.unit_rectangle().deepcopy()
exterior.vertices *= 4
exterior.vertices -= 2
interior = mpath.Path.unit_circle().deepcopy()
interior.vertices = interior.vertices[::-1]
clip_path = mpath.Path(vertices=np.concatenate([exterior.vertices,
interior.vertices]),
codes=np.concatenate([exterior.codes,
interior.codes]))
star = mpath.Path.unit_regular_star(6).deepcopy()
star.vertices *= 2.6
ax1 = plt.subplot(121)
col = mcollections.PathCollection([star], lw=5, edgecolor='blue',
facecolor='red', alpha=0.7, hatch='*')
col.set_clip_path(clip_path, ax1.transData)
ax1.add_collection(col)
ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)
patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red',
alpha=0.7, hatch='*')
patch.set_clip_path(clip_path, ax2.transData)
ax2.add_patch(patch)
ax1.set_xlim([-3, 3])
ax1.set_ylim([-3, 3])
示例6: plot_logpdf_Gaussian
def plot_logpdf_Gaussian():
y2 = -6
logvar = np.arange(-4,4,0.05)
logprior = np.array([lp_gaussian(lv, 0, 1) for lv in logvar])
def plot_logvar(mu):
lp = np.array([lp_gaussian(y2, mu, np.exp(lv)) for lv in logvar])
plt.plot(logvar, lp+logprior, label='mu = {}'.format(mu))
plt.ylim(-20,3)
plt.clf()
plt.subplot(2,1,1)
plt.plot(logvar, logprior, label='prior', lw=5)
plot_logvar(0)
plot_logvar(-6)
plt.xlabel('logvar')
plt.legend()
mu = np.arange(-8,8,0.05)
logprior = np.array([lp_gaussian(m,0,1) for m in mu])
def plot_mu(var):
lp = np.array([lp_gaussian(y2, m, var) for m in mu])
lp = lp + logprior
plt.plot(mu, lp, label='var = {}'.format(var))
plt.ylim(-30,0)
plt.subplot(2,1,2)
plt.plot(mu, logprior, label='prior', lw=5)
plot_mu(0.1)
plot_mu(1.0)
plot_mu(10)
plt.xlabel('mu')
plt.legend()
示例7: template_matching
def template_matching():
img = cv2.imread('messi.jpg',0)
img2 = img.copy()
template = cv2.imread('face.png',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
# Apply template Matching
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img,top_left, bottom_right, 255, 2)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
示例8: __call__
def __call__(self,u,w,bx,by,bz,b2,t):
q = 8
map = cm.red_blue()
if self.x == None:
nx = u.shape[2]
nz = u.shape[0]
self.x,self.y = np.meshgrid(range(nx),range(nz))
x,y = self.x,self.y
avgu = np.average(u,1)
avgw = np.average(w,1)
avgbx = np.average(bx,1)
avgby = np.average(by,1)
avgbz = np.average(bz,1)
avgb2 = np.average(b2,1)
avgt = np.average(t,1)
plt.subplot(121)
plt.imshow(avgt,cmap=map,origin='lower')
plt.colorbar()
plt.quiver(x[::q,::q],y[::q,::q],avgu[::q,::q],avgw[::q,::q])
plt.title('Tracer-Vel')
plt.axis("tight")
plt.subplot(122)
plt.imshow(avgby,cmap=map,origin='lower')
plt.colorbar()
plt.quiver(x[::q,::q],y[::q,::q],avgbx[::q,::q],avgbz[::q,::q])
plt.title('By-Twist')
plt.axis("tight")
示例9: subplot
def subplot(self,names,title=None,style=None):
assert isinstance(names,list)
fig = plt.figure()
if title is None:
if isinstance(names,str):
title = names
else:
assert isinstance(names,list)
if len(names) == 1:
title = names[0]
else:
title = str(names)
fig.canvas.set_window_title(str(title))
plt.clf()
n = len(names)
if style is None:
style = [None]*n
for k,name in enumerate(names):
plt.subplot(n,1,k+1)
if k==0:
self._plot(name,title,style=style[k])
else:
self._plot(name,None,style=style[k])
示例10: ReleaseMemoryPlot2
def ReleaseMemoryPlot2(mincut = 0.9, maxcut = 1, N = 100):
step = (maxcut - mincut)/N
cuts = [mincut + step*i for i in range(0, N+1)]
released_memory = []
good_memory = []
part_of_good_memory = []
all_memory = signal_test2.get_data(['DiskSize']).values[:,0].sum() + bck_test2.get_data(['DiskSize']).values[:,0].sum()
memory_can_be_free = signal_test2.get_data(['DiskSize']).values[:,0].sum()
for i in cuts:
rm, gm, pm = ReleaseMemory2(cut = i)
released_memory.append(rm)
good_memory.append(gm)
part_of_good_memory.append(pm)
print 'all_memory = ', all_memory
print 'memory_can_be_free = ', memory_can_be_free
plt.subplot(1,1,1)
plt.plot(cuts, released_memory, 'b', label = 'released memory')
plt.plot(cuts, good_memory, 'r', label = 'good memory')
plt.legend(loc = 'best')
plt.show()
plt.subplot(1,1,1)
plt.plot(cuts, part_of_good_memory, 'r', label = 'part of good memory')
plt.legend(loc = 'best')
plt.show()
示例11: make_intergenerational_figure
def make_intergenerational_figure(data, lowerbound, upperbound, rows, title):
plt.figure(figsize=(10,10))
plt.suptitle(title,fontsize=20)
for index in range(4):
plt.subplot(2,2,index+1)
#simulation distribution
plt.hist(accepted[:,rows[index]], normed=True, bins = range(0,100,5), color = col)
#simulation values
value = np.mean(accepted[:,rows[index]])
std = 2*np.std(accepted[:,rows[index]])
plt.errorbar((value,), (red_marker_location-0.02), xerr=((std,),(std,)),
color=col, fmt='o', linewidth=2, capsize=5, mec = col)
#survey values
value = data[index]
lb = lowerbound[index]
ub = upperbound[index]
plt.errorbar((value,), (red_marker_location,), xerr=((value-lb,),(ub-value,)),
color='r', fmt='o', linewidth=2, capsize=5, mec = 'r')
#labeling
plt.ylim(0,ylimit)
plt.xlim(0,100)
#make subplots pretty
plt.subplot(2,2,1)
plt.title("Males")
plt.ylabel("'05\nFrequency")
plt.subplot(2,2,2)
plt.title("Females")
plt.subplot(2,2,3)
plt.ylabel("'08\nFrequency")
plt.xlabel("Percent Responding Affirmatively")
plt.subplot(2,2,4)
plt.xlabel("Percent Responding Affirmatively")
示例12: visualize_singular_values
def visualize_singular_values(args):
param_values = load_parameter_values(args.load_path)
for d in range(args.layers):
if args.rnn_type == 'lstm':
ws = param_values["/recurrentstack/lstm_" + str(d) + ".W_state"]
w_rec = ws[:, 3 * args.state_dim:]
elif args.rnn_type == 'simple':
w_rec = param_values["/recurrentstack/simplerecurrent_" + str(d) +
".W_state"]
else:
raise NotImplementedError
U, s, V = np.linalg.svd(w_rec, full_matrices=True)
plt.subplot(2, 1, 1)
plt.plot(np.arange(s.shape[0]), s, label='Layer_' + str(d))
plt.grid(True)
plt.legend(loc='upper right')
plt.title("Singular_values_of_recurrent_weights")
plt.subplot(2, 1, 2)
plt.plot(np.arange(s.shape[0]), np.log(s + 1E-15),
label='Layer_' + str(d))
plt.grid(True)
plt.title("Log_singular_values_of_recurrent_weights")
plt.tight_layout()
plt.savefig(args.save_path + "/visualize_singular_values.png")
logger.info("Figure \"visualize_singular_values"
".png\" saved at directory: " + args.save_path)
示例13: plotMultiGameTaskResults
def plotMultiGameTaskResults(directory, game, numTasks = 2):
filename = directory + game
fullShareResultsFilename = filename + "_fullShare.csv"
layerShareResultsFilename = filename + "_layerShare.csv"
repShareResultsFilename = filename + "_repShare.csv"
games = game.split(",")
if len(games) != numTasks:
print "The number of games is not equal to the number of tasks - not plotting"
return
fullResults = getResultsFromFile(fullShareResultsFilename, numTasks)
layerResults = getResultsFromFile(layerShareResultsFilename, numTasks)
repResults = getResultsFromFile(repShareResultsFilename, numTasks)
# figure = plt.figure()
# subplot = figure.add_subplot(111)
# plots = []
# for i in xrange(numTasks):
# plots.append(subplot.plot(fullResults[0][0:len(fullResults[1][i])], fullResults[1][i], label="FullShare: " + str(i)))
# figure.suptitle(title)
for i in xrange(len(games)):
plt.figure(i + 1)
plt.subplot(111)
plt.plot(fullResults[0][0:len(fullResults[1][i])], fullResults[1][i], label="Full Share")
plt.plot(layerResults[0][0:len(layerResults[1][i])], layerResults[1][i], label="Layer Share")
plt.plot(repResults[0][0:len(repResults[1][i])], repResults[1][i], label="Rep Share")
plt.xlabel('epochs')
plt.ylabel('Average Reward')
plt.title(games[i])
L = plt.legend()
L.draggable(state=True)
示例14: calc_snr
def calc_snr(plot = False):
tx = fromfile(open('tx_sym.32fc'), dtype=complex64)
rx = fromfile(open('rx_sym.32fc'), dtype=complex64)
if (len(tx) == 0 or len(rx) == 0):
print 'Not valid data'
print '\tPlease run gnuradio simulation first'
exit(-1)
size = min([len(tx), len(rx)]) - 1
rx = rx[0:size]
tx = tx[0:size]
tx_power = sum([abs(tx[i])**2 for i in range(size)])
rx_power = sum([abs(rx[i])**2 for i in range(size)])
noise_power = sum([abs(tx[i] - rx[i])**2 for i in range(size)])
SNR = 1.0*tx_power/noise_power
SNR_dB = 10*log10(SNR)
if plot:
init = 0
end = 100
p.subplot(211)
p.plot(list(real(tx[init:end])), '-o')
p.plot(list(imag(tx[init:end])), '-o')
p.subplot(212)
p.plot(list(real(rx[init:end])), '-o')
p.plot(list(imag(rx[init:end])), '-o')
p.show()
return SNR_dB
示例15: plot_main_seeds
def plot_main_seeds(self, qname, radio=False, checkbox=False,
numerical=False, array=False):
""" Plot the responses separately for each seed group in main_seeds. """
assert sum([radio, checkbox, numerical, array]) == 1
for seed in self.main_seeds:
responses_seed = self.filter_rows_by_seed(seed, self.responses)
responses_seed_question = self.filter_columns_by_name(qname, responses_seed)
plt.subplot(int("22" + str(self.main_seeds.index(seed))))
plt.title("Seed " + seed)
if radio:
self.plot_convergence_radio(qname, responses_seed_question)
elif checkbox:
self.plot_convergence_checkbox(responses_seed_question)
elif numerical:
self.plot_convergence_numerical(responses_seed_question)
elif array:
self.plot_array_boxes(qname, responses_seed_question)
qtext = self.get_qtext_from_qname(qname)
plt.suptitle(qtext)
plt.tight_layout()
plt.show()