def despine(fig=None, ax=None, top=True, right=True,
left=False, bottom=False):
"""Remove the top and right spines from plot(s).
fig : matplotlib figure
figure to despine all axes of, default uses current figure
ax : matplotlib axes
specific axes object to despine
top, right, left, bottom : boolean
if True, remove that spine
"""
if fig is None and ax is None:
axes = plt.gcf().axes
elif fig is not None:
axes = fig.axes
elif ax is not None:
axes = [ax]
for ax_i in axes:
for side in ["top", "right", "left", "bottom"]:
ax_i.spines[side].set_visible(not locals()[side])
python类figure()的实例源码
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
"""
Tune the subplot layout via the meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
plt.draw_if_interactive()
def setNmajors(xval=None, yval=None, ax=None, mode='auto', **kwargs):
"""
setNmajors - set major tick number
see figure.MaxNLocator for kwargs
"""
if ax is None:
ax = plt.gca()
if (mode == 'fixed'):
if xval is not None:
ax.xaxis.set_major_locator(MaxNLocator(xval, **kwargs))
if yval is not None:
ax.yaxis.set_major_locator(MaxNLocator(yval, **kwargs))
elif (mode == 'auto'):
if xval is not None:
ax.xaxis.set_major_locator(AutoLocator(xval, **kwargs))
if yval is not None:
ax.yaxis.set_major_locator(AutoLocator(yval, **kwargs))
plt.draw_if_interactive()
def test_axes():
try:
import matplotlib
version = matplotlib.__version__.split("-")[0]
version = version.split(".")[:2]
if [int(_) for _ in version] < [0,99]:
raise ImportError
import pylab
except ImportError:
print("\nSkipping test (pylab not available or too old version)\n")
return
fig = pylab.figure()
axes = fig.add_subplot(111)
for ctx in [mp, fp]:
ctx.plot(lambda x: x**2, [0, 3], axes=axes)
assert axes.get_xlabel() == 'x'
assert axes.get_ylabel() == 'f(x)'
fig = pylab.figure()
axes = fig.add_subplot(111)
for ctx in [mp, fp]:
ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes)
assert axes.get_xlabel() == 'Re(z)'
assert axes.get_ylabel() == 'Im(z)'
def plot_reg_2D_stoc(X,stoc_vector):
deter_vec = np.invert(stoc_vector)
dom_max = np.amax(X[stoc_vector,:]) + 1
A = np.zeros((dom_max,dom_max))
stoc_indexs = np.arange(0,X.shape[0],1)[stoc_vector].astype(int)
for i,deter_element in enumerate(deter_vec):
if deter_element == True:
A[X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int)] = X[i,:]
pl.figure(i)
#ax = fig.gca(projection='3d')
#surf = ax.plot_surface(X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int),X[i,:], rstride=1, cstride=1,
#cmap=cm.coolwarm,linewidth=0, antialiased=False)
pl.contour(A,X[i,:])
#ax.zaxis.set_major_locator(LinearLocator(10))
#ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
#fig.colorbar(surf, shrink=0.5, aspect=5)
pl.show()
def test():
points = square_points(10)
distance = np.zeros((100,100))
for (i, pointi) in enumerate(points):
for (j, pointj) in enumerate(points):
distance[i, j] = norm(pointi - pointj)
Y, eigs = mds(distance)
pylab.figure(1)
pylab.plot(Y[:, 0], Y[:, 1], '.')
pylab.figure(2)
pylab.plot(points[:, 0], points[:, 1], '.')
pylab.show()
def show_particles(rbm, state, dataset, display=True, figname='PCD particles', figtitle='PCD particles',
size=None):
try:
fantasy_vis = rbm.vis_expectations(state.h)
except:
fantasy_vis = state
if size is None:
size = (dataset.num_rows, dataset.num_cols)
imgs = [fantasy_vis[j, :np.prod(size)].reshape(size).as_numpy_array()
for j in range(fantasy_vis.shape[0])]
visual = misc.norm01(misc.pack(imgs))
if display:
pylab.figure(figname)
pylab.matshow(visual, cmap='gray', fignum=False)
pylab.title(figtitle)
return visual
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True,
figname='Gibbs chains', figtitle='Gibbs chains'):
samples = gnp.zeros((num_particles, num_samples, state.v.shape[1]))
state = state[:num_particles, :, :]
for i in range(num_samples):
samples[:, i, :] = rbm.vis_expectations(state.h)
for j in range(show_every):
state = rbm.step(state)
npix = dataset.num_rows * dataset.num_cols
rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array()
for j in range(num_samples)],
normalize=False)
for i in range(num_particles)]
grid = vm.vjoin(rows, normalize=False)
if display:
pylab.figure(figname)
pylab.matshow(grid, cmap='gray', fignum=False)
pylab.title(figtitle)
pylab.gcf().canvas.draw()
return grid
def plot_eigenspectrum(G, s, nvis, nhid):
with misc.gnumpy_conversion_check('allow'):
dim = G.shape[0]
d, Q = scipy.linalg.eigh(G)
d = d[::-1]
Q = Q[:, ::-1]
pts = np.unique(np.floor(np.logspace(0., np.log10(dim-1), 500)).astype(int)) - 1
cf = [fisher.correlation_fraction(Q[:, i], s, nvis, nhid) for i in pts]
pylab.figure()
pylab.subplot(2, 1, 1)
pylab.loglog(range(1, dim+1), d, 'b-', lw=2.)
pylab.xticks([])
pylab.yticks(fontsize='large')
pylab.subplot(2, 1, 2)
pylab.semilogx(pts+1, cf, 'r-', lw=2.)
pylab.xticks(fontsize='x-large')
pylab.yticks(fontsize='large')
def view_positions(self, indices=None, time=None):
if time is None:
time = 0
res = self.synthetic_store.get(indices=indices, variables=['x', 'y', 'z'])
pylab.figure()
all_x = []
all_y = []
all_z = []
all_c = []
for key in res.keys():
all_x += [res[key]['x'][time]]
all_y += [res[key]['y'][time]]
all_z += [res[key]['z'][time]]
all_c += [self._scalarMap_synthetic.to_rgba(int(key))]
pylab.scatter(self.probe.positions[0, :], self.probe.positions[1, :], c='k')
pylab.scatter(all_x, all_y, c=all_c)
pylab.show()
def ansQuest(maxTime,numTrials):
means=[]
distLists=performSim(maxTime,numTrials)
for t in range(maxTime+1):
tot=0.0
for distL in distLists:
tot+=distL[t]
means.append(tot/len(distL))
pylab.figure()
pylab.plot(means)
pylab.xlabel('distance')
pylab.ylabel('time')
pylab.title('Average Distance vs. Time ('+str(len(distLists))+'trials)')
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
# Receptive Fields Summary
try:
W = layer.W
except:
W = layer
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fig = mpl.figure(figOffset); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,np.shape(fields)[0]):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
try:
W = layer.output
except:
W = layer
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
# Receptive Fields Summary
W = layer.W
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
fieldsN = min(fields.shape[0],maxFields)
perRow = int(math.floor(math.sqrt(fieldsN)))
perColumn = int(math.ceil(fieldsN/float(perRow)))
fig = mpl.figure(figName); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,fieldsN):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
W = layer.output
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):
nb_templates = templates.shape[1]
n_panels = numpy.ceil(numpy.sqrt(nb_templates))
mask = numpy.where(halo > -1)[0]
clust_idx = numpy.unique(halo[mask])
fig = pylab.figure()
square = True
center = len(data[0] - 1)//2
for count, i in enumerate(xrange(nb_templates)):
if square:
pylab.subplot(n_panels, n_panels, count + 1)
if (numpy.mod(count, n_panels) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_panels*(n_panels - 1)):
pylab.setp(pylab.gca(), xticks=[])
subcurves = numpy.where(halo == clust_idx[count])[0]
for k in numpy.random.permutation(subcurves)[:n_curves]:
pylab.plot(data[k], '0.5')
pylab.plot(templates[:, count], 'r')
pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)
xmin, xmax = pylab.xlim()
pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
#pylab.ylim(-1.5*threshold, 1.5*threshold)
ymin, ymax = pylab.ylim()
pylab.plot([center, center], [ymin, ymax], 'k--')
pylab.title('Cluster %d' %i)
if nb_templates > 0:
pylab.tight_layout()
if save:
pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def view_artefact(data, save=False):
fig = pylab.figure()
pylab.plot(data.T)
if save:
pylab.savefig(os.path.join(save[0], 'artefact_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def view_raw_templates(file_name, n_temp=2, square=True):
N_e, N_t, N_tm = templates.shape
if not numpy.iterable(n_temp):
if square:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2]
else:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp]
else:
idx = n_temp
import matplotlib.colors as colors
my_cmap = pylab.get_cmap('winter')
cNorm = colors.Normalize(vmin=0, vmax=N_e)
scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap)
pylab.figure()
for count, i in enumerate(idx):
if square:
pylab.subplot(n_temp, n_temp, count + 1)
if (numpy.mod(count, n_temp) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_temp*(n_temp - 1)):
pylab.setp(pylab.gca(), xticks=[])
else:
pylab.subplot(len(idx), 1, count + 1)
if count != (len(idx) - 1):
pylab.setp(pylab.gca(), xticks=[])
for j in xrange(N_e):
colorVal = scalarMap.to_rgba(j)
pylab.plot(templates[j, :, i], color=colorVal)
pylab.title('Template %d' %i)
pylab.tight_layout()
pylab.show()
def view_trigger_snippets(trigger_snippets, chans, save=None):
# Create output directory if necessary.
if os.path.exists(save):
for f in os.listdir(save):
p = os.path.join(save, f)
os.remove(p)
os.removedirs(save)
os.makedirs(save)
# Plot figures.
fig = pylab.figure()
for (c, chan) in enumerate(chans):
ax = fig.add_subplot(1, 1, 1)
for n in xrange(0, trigger_snippets.shape[2]):
y = trigger_snippets[:, c, n]
x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
b = 0.5 + 0.5 * numpy.random.rand()
ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
y = numpy.mean(trigger_snippets[:, c, :], axis=1)
x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid')
ax.grid(True)
ax.set_xlim([numpy.amin(x), numpy.amax(x)])
ax.set_title("Channel %d" %chan)
ax.set_xlabel("time")
ax.set_ylabel("amplitude")
if save is not None:
# Save plot.
filename = "channel-%d.png" %chan
path = os.path.join(save, filename)
pylab.savefig(path)
fig.clf()
if save is None:
pylab.show()
else:
pylab.close(fig)
return
def view_mahalanobis_distribution(data_1, data_2, save=None):
'''Plot Mahalanobis distribution Before and After'''
fig = pylab.figure()
ax = fig.add_subplot(1,2,1)
if len(data_1) == 3:
d_gt, d_ngt, d_noi = data_1
elif len(data_1) == 2:
d_gt, d_ngt = data_1
if len(data_1) == 3:
ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
ax.grid(True)
ax.set_title("Before")
ax.set_ylabel("")
ax.set_xlabel('# Samples')
ax.set_xlabel('Distances')
if len(data_2) == 3:
d_gt, d_ngt, d_noi = data_2
elif len(data_2) == 2:
d_gt, d_ngt = data_2
ax = fig.add_subplot(1,2,2)
if len(data_2) == 3:
ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
ax.grid(True)
ax.set_title("After")
ax.set_ylabel("")
ax.set_xlabel('Distances')
ax.legend()
if save is None:
pylab.show()
else:
pylab.savefig(save)
pylab.close(fig)
return