def nicecolorbar(self,
axcb=None,
reflevel=None,
label=None,
vmax=None,
vmin=None,
data=None,
loc='head right',
fontsize=8,
ticks = None):
if not axcb:
axcb = matplotlib.pyplot.gca()
divider = make_axes_locatable(axcb)
# this code is from
# http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1
cax = divider.append_axes("right", size="2%", pad=0.15)
levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000])
if vmax!= None and vmin != None:
level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))]
ticks = numpy.arange(vmin, vmax, level)
elif vmax :
level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))]
ticks = numpy.arange(numpy.nanmin(data), vmax, level)
elif data is not None:
level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))]
ticks = None #numpy.arange(numpy.nanmin(data), numpy.nanmax(data), level)
#ticks -= numpy.nanmin(abs(ticks))
cb = matplotlib.pyplot.colorbar(self,
cax=cax,
label=label,
orientation='vertical',
extend='both',
spacing='uniform',
ticks=ticks)
if vmax!= None and vmin != None:
#print(ticks,vmin,vmax)
cb.set_clim(vmin, vmax)
cb.ax.yaxis.set_ticks_position('right')
cb.ax.yaxis.set_label_position('right')
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation='vertical',fontsize=fontsize)
#if reflevel:
# cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color='k',linewidth=2)
return cb
python类make_axes_locatable()的实例源码
def colorbar(self,mappable=None,location='right',size="5%",pad='2%',fig=None,ax=None,**kwargs):
"""
Add colorbar to axes associated with a map.
The colorbar axes instance is created using the axes_grid toolkit.
.. tabularcolumns:: |l|L|
============== ====================================================
Keywords Description
============== ====================================================
mappable the Image, ContourSet, etc. to which the colorbar
applies. Default None, matplotlib.pyplot.gci() is
used to retrieve the current image mappable.
location where to put colorbar ('top','bottom','left','right')
Default 'right'.
size width of colorbar axes (string 'N%', where N is
an integer describing the fractional width of the parent
axes). Default '5%'.
pad Padding between parent axes and colorbar axes in
same units as size. Default '2%'.
fig Figure instance the map axes instance is associated
with. Default None, and matplotlib.pyplot.gcf() is used
to retrieve the current active figure instance.
ax The axes instance which the colorbar will be
associated with. Default None, searches for self.ax,
and if None uses matplotlib.pyplot.gca().
\**kwargs extra keyword arguments passed on to
colorbar method of the figure instance.
============== ====================================================
Returns a matplotlib colorbar instance.
"""
# get current axes instance (if none specified).
ax = ax or self._check_ax()
# get current figure instance (if none specified).
if fig is None or mappable is None:
import matplotlib.pyplot as plt
if fig is None:
fig = plt.gcf()
# get current mappable if none specified.
if mappable is None:
mappable = plt.gci()
# create colorbar axes uses axes_grid toolkit.
divider = make_axes_locatable(ax)
if location in ['left','right']:
orientation = 'vertical'
elif location in ['top','bottom']:
orientation = 'horizontal'
else:
raise ValueError('location must be top,bottom,left or right')
cax = divider.append_axes(location, size=size, pad=pad)
# create colorbar.
cb = fig.colorbar(mappable,orientation=orientation,cax=cax,**kwargs)
fig.sca(ax) # reset parent axes as current axes.
return cb
def colorbar(self,mappable=None,location='right',size="5%",pad='2%',fig=None,ax=None,**kwargs):
"""
Add colorbar to axes associated with a map.
The colorbar axes instance is created using the axes_grid toolkit.
.. tabularcolumns:: |l|L|
============== ====================================================
Keywords Description
============== ====================================================
mappable the Image, ContourSet, etc. to which the colorbar
applies. Default None, matplotlib.pyplot.gci() is
used to retrieve the current image mappable.
location where to put colorbar ('top','bottom','left','right')
Default 'right'.
size width of colorbar axes (string 'N%', where N is
an integer describing the fractional width of the parent
axes). Default '5%'.
pad Padding between parent axes and colorbar axes in
same units as size. Default '2%'.
fig Figure instance the map axes instance is associated
with. Default None, and matplotlib.pyplot.gcf() is used
to retrieve the current active figure instance.
ax The axes instance which the colorbar will be
associated with. Default None, searches for self.ax,
and if None uses matplotlib.pyplot.gca().
\**kwargs extra keyword arguments passed on to
colorbar method of the figure instance.
============== ====================================================
Returns a matplotlib colorbar instance.
"""
# get current axes instance (if none specified).
ax = ax or self._check_ax()
# get current figure instance (if none specified).
if fig is None or mappable is None:
import matplotlib.pyplot as plt
if fig is None:
fig = plt.gcf()
# get current mappable if none specified.
if mappable is None:
mappable = plt.gci()
# create colorbar axes uses axes_grid toolkit.
divider = make_axes_locatable(ax)
if location in ['left','right']:
orientation = 'vertical'
elif location in ['top','bottom']:
orientation = 'horizontal'
else:
raise ValueError('location must be top,bottom,left or right')
cax = divider.append_axes(location, size=size, pad=pad)
# create colorbar.
cb = fig.colorbar(mappable,orientation=orientation,cax=cax,**kwargs)
fig.sca(ax) # reset parent axes as current axes.
return cb
def plot_spikes(in_file, in_fft, spikes_list, cols=3,
labelfmt='t={0:.3f}s (z={1:d})',
out_file=None):
from mpl_toolkits.axes_grid1 import make_axes_locatable
nii = nb.as_closest_canonical(nb.load(in_file))
fft = nb.load(in_fft).get_data()
data = nii.get_data()
zooms = nii.header.get_zooms()[:2]
tstep = nii.header.get_zooms()[-1]
ntpoints = data.shape[-1]
if len(spikes_list) > cols * 7:
cols += 1
nspikes = len(spikes_list)
rows = 1
if nspikes > cols:
rows = math.ceil(nspikes / cols)
fig = plt.figure(figsize=(7 * cols, 5 * rows))
for i, (t, z) in enumerate(spikes_list):
prev = None
pvft = None
if t > 0:
prev = data[..., z, t - 1]
pvft = fft[..., z, t - 1]
post = None
psft = None
if t < (ntpoints - 1):
post = data[..., z, t + 1]
psft = fft[..., z, t + 1]
ax1 = fig.add_subplot(rows, cols, i + 1)
divider = make_axes_locatable(ax1)
ax2 = divider.new_vertical(size="100%", pad=0.1)
fig.add_axes(ax2)
plot_slice_tern(data[..., z, t], prev=prev, post=post, spacing=zooms,
ax=ax2,
label=labelfmt.format(t * tstep, z))
plot_slice_tern(fft[..., z, t], prev=pvft, post=psft, vmin=-5, vmax=5,
cmap=get_parula(), ax=ax1)
plt.tight_layout()
if out_file is None:
fname, ext = op.splitext(op.basename(in_file))
if ext == '.gz':
fname, _ = op.splitext(fname)
out_file = op.abspath('%s.svg' % fname)
fig.savefig(out_file, format='svg', dpi=300, bbox_inches='tight')
return out_file
def make_mutual_info_plot(fn):
M.rcParams.update({'font.size': 11})
angleList = N.array([f/f.max() for f in read.extract_arr_from_h5(fn, "/history/angle", n=-1)])
mutualInfoList = read.extract_arr_from_h5(fn, "/history/mutual_info", n=-1)
quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
quatSwitchPos = N.where(quatList[:-1]-quatList[1:] != 0)[0] + 1
angsort = N.argsort(angleList[-1])
misort = N.argsort(mutualInfoList.mean(axis=0))
blkPositions = [0] + list(quatSwitchPos) + [-1]
for bp in range(len(blkPositions)-1):
(start, end) = (blkPositions[bp], blkPositions[bp+1])
curr_blk = angleList[start:end]
curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[0]])
# curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[bp]])
if len(curr_blk) == 0:
pass
else:
angsort = N.argsort(curr_blk[-1])
angleList[start:end] = curr_blk[:,angsort]
for n,l in enumerate(curr_blk2):
misort = N.argsort(l)
mutualInfoList[start+n] = l[misort]
P.ioff()
fig, ax = P.subplots(2, 1, sharex=True, figsize=(7, 10))
fig.subplots_adjust(hspace=0.1)
im0 = ax[0].imshow(angleList.transpose(), aspect='auto', interpolation=None, cmap=P.cm.OrRd)
ax[0].set_xlabel("iteration")
ax[0].set_ylabel("each pattern's most likely orientation\n(sorted by final orientation in each block)")
(e_min, e_max) = (1, len(angleList[0]))
e_int = 0.1*(e_max-e_min)
ax[0].plot([0, 0], [e_min, e_max], 'k-')
ax[0].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
for n,qs in enumerate(quatSwitchPos):
ax[0].plot([qs, qs], [e_min, e_max], 'k-')
ax[0].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') )
div0 = make_axes_locatable(ax[0])
cax0 = div0.append_axes("right", size="5%", pad=0.05)
cbar0 = P.colorbar(im0, cax=cax0)
ax[0].set_ylim(e_min, e_max)
ax[0].set_xlim(0, len(angleList)-1)
(e_min, e_max) = (1, len(mutualInfoList[0]))
e_int = 0.1*(e_max-e_min)
im1 = ax[1].imshow(mutualInfoList.transpose(), vmax=.2, aspect='auto', cmap=P.cm.YlGnBu)
ax[1].set_xlabel("iteration")
ax[1].set_ylabel("average mutual-information per dataset\n(sorted by average information)")
ax[1].plot([0, 0], [e_min, e_max], 'k-')
ax[1].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
for n,qs in enumerate(quatSwitchPos):
ax[1].plot([qs, qs], [e_min, e_max], 'k-')
ax[1].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') )
div1 = make_axes_locatable(ax[1])
cax1 = div1.append_axes("right", size="5%", pad=0.05)
cbar1 = P.colorbar(im1, cax=cax1)
ax[1].set_ylim(e_min, e_max)
ax[1].set_xlim(0, len(mutualInfoList)-1)
img_name = "mutual_info_plot.pdf"
P.savefig(img_name, bbox_inches='tight')
print("Image has been saved as %s" % img_name)
P.close(fig)
def get_plot_axes(self, figure=None, ax_xy=None):
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
xmin, xmax, ymin, ymax, zmin, zmax = self.get_extent()
if figure is None and ax_xy is None:
figure = plt.figure()
if figure is None and ax_xy is not None:
figure = ax_xy.get_figure()
if ax_xy is None:
ax_xy = figure.add_subplot(111)
ratio = float(xmax - xmin) / (ymax - ymin)
plot_xz_size = ((zmax - zmin)/(xmax - xmin))*100
plot_yz_size = plot_xz_size / ratio
plot_cbar_size = 5 # percent
xz_size = '%f %%' % plot_xz_size
yz_size = '%f %%' % plot_yz_size
cb_size = '%f %%' % plot_cbar_size
# ax_xy
divider = make_axes_locatable(ax_xy)
plt.setp(ax_xy.get_xticklabels(), visible=False)
ax_xy.set_xlim(xmin, xmax)
ax_xy.set_ylim(ymin, ymax)
ax_xy.set_aspect('equal', 'datalim')
plt.setp(ax_xy.get_yticklabels(), rotation=90, fontsize=12)
# ax_yz
ax_yz = divider.append_axes('right', size=yz_size, pad=0.05,
sharey=ax_xy)
plt.setp(ax_yz.get_yticklabels(), visible=False)
ax_yz.set_xlim(zmin, zmax)
ax_yz.set_ylim(ymin, ymax)
plt.setp(ax_yz.get_xticklabels(), rotation=90, fontsize=12)
plt.setp(ax_yz.get_yticklabels(), rotation=90, fontsize=12)
# ax_xz
ax_xz = divider.append_axes('bottom', size=xz_size, pad=0.05,
sharex=ax_xy)
ax_xz.set_xlim(xmin, xmax)
ax_xz.set_ylim(zmax, zmin)
# color-bar
ax_cb = divider.append_axes('bottom', size=cb_size, pad=0.5)
return ax_xy, ax_xz, ax_yz, ax_cb
def lblshow(label_img, labels_str=None, f=None, ax=None, cmap=None, *args, **kwargs):
''' display a labeled image with associated legend
Parameters
----------
label_img : labeled image [nrows, ncols] = numpy.array.shape
labels_str : a complete list of labels
f : (optional) a figure handle
cmap : the color of each label (optional). like a list of colors, e.g.,
['Red','Green',...] or a matplotlib.colors.ListedColormap)
'''
if labels_str is None:
labels_str = [str(i) for i in np.unique(label_img)]
if ax is None:
if f is None:
f,ax = plt.subplots(1,1)
f.set_size_inches(9,6)
else:
ax = f.gca()
elif f is None:
f = ax.get_figure()
nlabels = len(labels_str)
if type(cmap) is mpl.colors.ListedColormap:
pass
elif hasattr(cmap, '__iter__'):
if not kwargs.has_key('norm'):
bounds = range(0,len(cmap)+1)
kwargs['norm'] = mpl.colors.BoundaryNorm(bounds, len(cmap)) # HACKY
cmap = mpl.colors.ListedColormap(cmap)
elif cmap is None:
colors = mpl.cm.spectral(np.linspace(0, 1, nlabels))
cmap = mpl.colors.ListedColormap(colors)
else:
assert False, 'invalid color map'
im = ax.imshow(label_img, cmap=cmap, *args, **kwargs); ax.axis('off')
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax)
cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(labels_str):
cbar.ax.text(1.3, float(2 * j + 1) / (nlabels*2), lab, ha='left', va='center')
return f
def plot_all_weights(model, n=64, n_columns=3, **kwargs):
"""
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Set default matplotlib parameters
if not 'interpolation' in kwargs.keys():
kwargs['interpolation'] = "none"
if not 'cmap' in kwargs.keys():
kwargs['cmap'] = "gray"
layers_to_show = []
for i, layer in enumerate(model.layers):
if hasattr(layer, "W"):
weights = layer.W.get_value()
if weights.ndim == 4:
layers_to_show.append((i, layer))
n_mosaic = len(layers_to_show)
nrows = n_mosaic // n_columns
ncols = n_columns
if ncols ** 2 < n_mosaic:
nrows +=1
fig_w = 15
fig_h = nrows * fig_w / ncols
fig = plt.figure(figsize=(fig_w, fig_h))
for i, (layer_id, layer) in enumerate(layers_to_show):
mosaic = get_weights_mosaic(model, layer_id=layer_id, n=n)
ax = fig.add_subplot(nrows, ncols, i+1)
im = ax.imshow(mosaic, **kwargs)
ax.set_title("Layer #{} called '{}' \nof type {}".format(layer_id, layer.name, layer.__class__.__name__))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
plt.colorbar(im, cax=cax)
ax.axis('off')
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
#fig.tight_layout()
return fig
def nodes_graph(self, colnum=0, show=False, printout=True):
"""Plot a 2D map with hexagonal nodes and weights values
Args:
colnum (int): The index of the weight that will be shown as colormap.
show (bool, optional): Choose to display the plot.
printout (bool, optional): Choose to save the plot to a file.
"""
centers = [[node.pos[0],node.pos[1]] for node in self.nodeList]
widthP=100
dpi=72
xInch = self.netWidth*widthP/dpi
yInch = self.netHeight*widthP/dpi
fig=plt.figure(figsize=(xInch, yInch), dpi=dpi)
if self.colorEx==True:
cols = [[np.float(node.weights[0]),np.float(node.weights[1]),np.float(node.weights[2])]for node in self.nodeList]
ax = hx.plot_hex(fig, centers, cols)
ax.set_title('Node Grid w Color Features', size=80)
printName='nodesColors.png'
else:
cols = [node.weights[colnum] for node in self.nodeList]
ax = hx.plot_hex(fig, centers, cols)
ax.set_title('Node Grid w Feature #' + str(colnum), size=80)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.0)
cbar=plt.colorbar(ax.collections[0], cax=cax)
cbar.set_label('Feature #' + str(colnum)+' value', size=80, labelpad=50)
cbar.ax.tick_params(labelsize=60)
plt.sca(ax)
printName='nodesFeature_'+str(colnum)+'.png'
if printout==True:
plt.savefig(printName, bbox_inches='tight', dpi=dpi)
if show==True:
plt.show()
if show!=False and printout!=False:
plt.clf()
def diff_graph(self, show=False, printout=True):
"""Plot a 2D map with nodes and weights difference among neighbouring nodes.
Args:
show (bool, optional): Choose to display the plot.
printout (bool, optional): Choose to save the plot to a file.
"""
neighbours=[]
for node in self.nodeList:
nodelist=[]
for nodet in self.nodeList:
if node != nodet and node.get_nodeDistance(nodet) <= 1.001:
nodelist.append(nodet)
neighbours.append(nodelist)
diffs = []
for node, neighbours in zip(self.nodeList, neighbours):
diff=0
for nb in neighbours:
diff=diff+node.get_distance(nb.weights)
diffs.append(diff)
centers = [[node.pos[0],node.pos[1]] for node in self.nodeList]
widthP=100
dpi=72
xInch = self.netWidth*widthP/dpi
yInch = self.netHeight*widthP/dpi
fig=plt.figure(figsize=(xInch, yInch), dpi=dpi)
ax = hx.plot_hex(fig, centers, diffs)
ax.set_title('Nodes Grid w Weights Difference', size=80)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.0)
cbar=plt.colorbar(ax.collections[0], cax=cax)
cbar.set_label('Weights Difference', size=80, labelpad=50)
cbar.ax.tick_params(labelsize=60)
plt.sca(ax)
printName='nodesDifference.png'
if printout==True:
plt.savefig(printName, bbox_inches='tight', dpi=dpi)
if show==True:
plt.show()
if show!=False and printout!=False:
plt.clf()
def densityPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd, type):
"""Stellar density plot"""
mag_g = data[mag_g_dred_flag]
mag_r = data[mag_r_dred_flag]
if type == 'stars':
filter = star_filter(data)
plt.title('Stellar Density')
elif type == 'galaxies':
filter = galaxy_filter(data)
plt.title('Galactic Density')
elif type == 'blue_stars':
filter = blue_star_filter(data)
plt.title('Blue Stellar Density')
iso_filter = (iso.separation(mag_g, mag_r) < 0.1)
# projection of image
proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC']) # filter & iso_filter
bound = 0.5 #1.
steps = 100.
bins = np.linspace(-bound, bound, steps)
signal = np.histogram2d(x, y, bins=[bins, bins])[0]
sigma = 0.01 * (0.25 * np.arctan(0.25*g_radius*60. - 1.5) + 1.3) # full range, arctan
convolution = scipy.ndimage.filters.gaussian_filter(signal, sigma/(bound/steps))
plt.pcolormesh(bins, bins, convolution.T, cmap='Greys')
plt.xlim(bound, -bound)
plt.ylim(-bound, bound)
plt.gca().set_aspect('equal')
plt.xlabel(r'$\Delta \alpha$ (deg)')
plt.ylabel(r'$\Delta \delta$ (deg)')
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size = '5%', pad=0)
plt.colorbar(cax=cax)
def hessPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
"""Hess plot"""
mag_g = data[mag_g_dred_flag]
mag_r = data[mag_r_dred_flag]
filter_s = star_filter(data)
plt.title('Hess')
c1 = SkyCoord(targ_ra, targ_dec, unit='deg')
r_near = 2.*g_radius # annulus begins at 3*g_radius away from centroid
r_far = np.sqrt(5.)*g_radius # annulus has same area as inner area
inner = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < g_radius)
outer = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg > r_near) & (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < r_far)
xbins = np.arange(-0.5, 1.1, 0.1)
ybins = np.arange(16., 24.5, 0.5)
foreground = np.histogram2d(mag_g[inner & filter_s] - mag_r[inner & filter_s], mag_g[inner & filter_s], bins=[xbins, ybins])
background = np.histogram2d(mag_g[outer & filter_s] - mag_r[outer & filter_s], mag_g[outer & filter_s], bins=[xbins, ybins])
fg = foreground[0].T
bg = background[0].T
fg_abs = np.absolute(fg)
bg_abs = np.absolute(bg)
mask_abs = fg_abs + bg_abs
mask_abs[mask_abs == 0.] = np.nan # mask signficiant zeroes
signal = fg - bg
signal = np.ma.array(signal, mask=np.isnan(mask_abs)) # mask nan
cmap = matplotlib.cm.viridis
cmap.set_bad('w', 1.)
plt.pcolormesh(xbins, ybins, signal, cmap=cmap)
plt.colorbar()
ugali.utils.plotting.drawIsochrone(iso, lw=2, c='k', zorder=10, label='Isocrhone')
plt.axis([-0.5, 1.0, 16, 24])
plt.gca().invert_yaxis()
plt.gca().set_aspect(1./4.)
plt.xlabel('g-r (mag)')
plt.ylabel('g (mag)')
#ax = plt.gca()
#divider = make_axes_locatable(ax)
#cax = divider.append_axes('right', size = '5%', pad=0)
#plt.colorbar(cax=cax)
def drawMembersCMD(self,data):
ax = plt.gca()
if isinstance(data,basestring):
filename = data
data = pyfits.open(filename)[1].data
xmin, xmax = -0.25,0.25
ymin, ymax = -0.25,0.25
mmin, mmax = 16., 24.
cmin, cmax = -0.5, 1.0
mbins = np.linspace(mmin, mmax, 150)
cbins = np.linspace(cmin, cmax, 150)
mag_1 = data[self.config['catalog']['mag_1_field']]
mag_2 = data[self.config['catalog']['mag_2_field']]
x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC'])
sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax)
sel_prob = data['PROB'][sel] > 5.e-2
index_sort = numpy.argsort(data['PROB'][sel][sel_prob])
plt.scatter(data['COLOR'][sel][~sel_prob], mag_1[sel][~sel_prob],
marker='o',s=2,c='0.75',edgecolor='none')
sc = pylab.scatter(data['COLOR'][sel][sel_prob][index_sort], mag_1[sel][sel_prob][index_sort],
c=data['PROB'][sel][sel_prob][index_sort],
marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1)
pylab.xlim(cmin, cmax)
pylab.ylim(mmax, mmin)
pylab.xlabel(r'$g - r$')
pylab.ylabel(r'$g$')
#axes[1].yaxis.set_major_locator(MaxNLocator(prune='lower'))
pylab.xticks([-0.5, 0., 0.5, 1.])
pylab.yticks(numpy.arange(mmax - 1., mmin - 1., -1.))
ugali.utils.plotting.drawIsochrone(self.isochrone, c='k', zorder=10)
pylab.text(0.05, 0.95, r'$\Sigma p_{i} = %i$'%(data['PROB'].sum()),
fontsize=10, horizontalalignment='left', verticalalignment='top', color='k', transform=pylab.gca().transAxes,
bbox=dict(facecolor='white', alpha=1., edgecolor='none'))
divider = make_axes_locatable(pylab.gca())
ax_cb = divider.new_horizontal(size="7%", pad=0.1)
plt.gcf().add_axes(ax_cb)
pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability')
ax_cb.yaxis.tick_right()
def draw_slices(hist, func=np.sum, **kwargs):
""" Draw horizontal and vertical slices through histogram """
from mpl_toolkits.axes_grid1 import make_axes_locatable
kwargs.setdefault('ls','-')
ax = plt.gca()
data = hist
# Slices
vslice = func(data,axis=0)
hslice = func(data,axis=1)
npix = np.array(data.shape)
#xlim,ylim = plt.array(zip([0,0],npix-1))
xlim = ax.get_xlim()
ylim = ax.get_ylim()
#extent = ax.get_extent()
#xlim =extent[:2]
#ylim = extent[2:]
# Bin centers
xbin = np.linspace(xlim[0],xlim[1],len(vslice))#+0.5
ybin = np.linspace(ylim[0],ylim[1],len(hslice))#+0.5
divider = make_axes_locatable(ax)
#gh2 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[2, 1])
hax = divider.append_axes("right", size=1.2, pad=0.05,sharey=ax,
axes_class=axes_divider.LocatableAxes)
hax.axis["left"].toggle(label=False, ticklabels=False)
#hax.plot(hslice, plt.arange(*ylim)+0.5,'-') # Bin center
hax.plot(hslice, ybin, **kwargs) # Bin center
hax.xaxis.set_major_locator(MaxNLocator(4,prune='both'))
hax.set_ylim(*ylim)
#gh1 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[0, 2])
vax = divider.append_axes("top", size=1.2, pad=0.05, sharex=ax,
axes_class=axes_divider.LocatableAxes)
vax.axis["bottom"].toggle(label=False, ticklabels=False)
vax.plot(xbin, vslice, **kwargs)
vax.yaxis.set_major_locator(MaxNLocator(4,prune='lower'))
vax.set_xlim(*xlim)
return vax,hax
def full_plot(data, pi, phi, pi_at, save_name=None):
# Plot a single example.
f, (ax1, ax2, ax3, ax4) = pyplot.subplots(4, 1)
std_x = data_std * data + data_mean
# std_x = data
x = numpy.cumsum(std_x[:, 1])
y = numpy.cumsum(std_x[:, 2])
size_x = x.max() - x.min() + 1.
size_y = y.max() - y.min() + 1.
f.set_size_inches(5. * size_x / size_y, 20.)
cuts = numpy.where(std_x[:, 0] == 1)[0]
start = 0
for cut_value in cuts:
ax1.plot(
x[start:cut_value], y[start:cut_value], 'k-', linewidth=1.5)
start = cut_value + 1
ax1.axis('equal')
ax1.axes.get_xaxis().set_visible(False)
ax1.axes.get_yaxis().set_visible(False)
def plot_matrix(data, ax):
im = ax.imshow(
data.T, aspect='auto', origin='lower', interpolation='nearest')
cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05)
pyplot.colorbar(im, cax=cax)
plot_matrix(phi, ax2)
plot_matrix(pi_at, ax3)
plot_matrix(pi, ax4)
if save_name is None:
pyplot.show()
else:
try:
pyplot.savefig(
save_name,
bbox_inches='tight',
pad_inches=0.5)
except Exception:
print "Error building image!: " + save_name
pyplot.close()
def plot_jet_image(
ax, image, vmin=1e-9, vmax=1e-2, cmap="jet", title="Intensity",
label_axes=True, visible_axes=False, show_colorbar=True, colorbar_inside=False):
"""Display jet image.
Args:
ax: matplotlib axes to plot on.
image: array representing image to plot.
vmin, vmax: min, max intensity values to plot.
"""
width, height = image.T.shape
dw, dh = 1./width, 1./height
if not (vmin is None) and not (vmax is None):
if vmin < 0:
norm = MidPointNorm(vmin=vmin, vmax=vmax)
ticks = None
else:
norm = LogNorm(vmin=vmin, vmax=vmax)
ticks = np.logspace(
np.log10(vmin), np.log10(vmax),
1 + np.log10(vmax) - np.log10(vmin))
else:
norm = None
ticks = None
p = ax.imshow(
image.T, extent=(-(1+dw), 1+dw, -(1+dh), 1+dh), origin='low',
interpolation='nearest', norm=norm, cmap=cmap)
if show_colorbar:
if colorbar_inside:
cax = ax.figure.add_axes([0.85, 0.08, 0.03, 0.82])
else:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(p, cax=cax, ticks=ticks)
cbar.set_label(title, rotation=90, fontsize=18)
cbar.ax.tick_params(labelsize=12)
if colorbar_inside:
cbar.ax.yaxis.set_ticks_position('left')
if label_axes:
ax.set_xlabel(r'$x_1$', fontsize=18)
ax.set_ylabel(r'$x_2$', fontsize=18)
ax.tick_params(axis='both', which='major', labelsize=12)
else:
ax.axes.get_xaxis().set_ticks([])
ax.axes.get_yaxis().set_ticks([])
ax.axes.get_xaxis().set_visible(visible_axes)
ax.axes.get_yaxis().set_visible(visible_axes)
if visible_axes:
for spine in ['top', 'bottom', 'left', 'right']:
ax.spines[spine].set_linewidth(1)
ax.spines[spine].set_color('k')
else:
for spine in ['top', 'bottom', 'left', 'right']:
ax.spines[spine].set_visible(False)
ax.axes.grid(False)
def plot_wiring_cs(wiring, den_borders, ax_borders, confidence_lvl,
binary, wd, add_fname='_CS'):
"""Same as plot_wiring, but using all contact sites
"""
fig = plt.figure()
ax = plt.gca()
max_val = np.max(wiring)
for k, b in enumerate(den_borders):
b += k * 1
wiring = np.concatenate((wiring[:b, :], np.ones((1, wiring.shape[1], 1)),
wiring[b:, :]), axis=0)
for k, b in enumerate(ax_borders):
b += k * 1
wiring = np.concatenate((wiring[:, :b], np.ones((wiring.shape[0], 1, 1)),
wiring[:, b:]), axis=1)
ax.matshow(np.max(wiring.transpose(1, 0, 2), axis=2), interpolation="none",
extent=[0, wiring.shape[0], wiring.shape[1], 0], cmap='gray')
ax.set_xlabel('Post', fontsize=18)
ax.set_ylabel('Pre', fontsize=18)
ax.set_xlim(0, wiring.shape[0])
ax.set_ylim(0, wiring.shape[1])
plt.grid(False)
plt.axis('off')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
a = np.array([[0, 1]])
plt.figure()
plt.imshow(a, cmap='gray')
plt.gca().set_visible(False)
cb = plt.colorbar(cax=cax, ticks=[0, 1])
if not binary:
cb.ax.set_yticklabels(['0', "%0.3g+" % max_val], rotation=90)
cb.set_label(u'Area of Synaptic Junctions [µm$^2$]')
else:
cb.ax.set_yticklabels(['0', '1'], rotation=90)
cb.set_label(u'Synaptic Junction')
plt.close()
if not binary:
fig.savefig(wd + '/figures/type_wiring%s_conf'
'lvl%d.png' % (add_fname, int(confidence_lvl*10)), dpi=600)
else:
fig.savefig(wd + '/figures/type_wiring%s_conf'
'lvl%d_binary.png' % (add_fname, int(confidence_lvl*10)), dpi=600)
def plot_all_weights(model, n=64, n_columns=3, **kwargs):
"""
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Set default matplotlib parameters
if not 'interpolation' in kwargs.keys():
kwargs['interpolation'] = "none"
if not 'cmap' in kwargs.keys():
kwargs['cmap'] = "gray"
layers_to_show = []
for i, layer in enumerate(model.layers):
if hasattr(layer, "W"):
weights = K.eval(layer.W.value())
if weights.ndim == 4:
layers_to_show.append((i, layer))
n_mosaic = len(layers_to_show)
nrows = n_mosaic // n_columns
ncols = n_columns
if ncols ** 2 < n_mosaic:
nrows +=1
fig_w = 15
fig_h = nrows * fig_w / ncols
fig = plt.figure(figsize=(fig_w, fig_h))
for i, (layer_id, layer) in enumerate(layers_to_show):
mosaic = get_weights_mosaic(model, layer_id=layer_id, n=n)
ax = fig.add_subplot(nrows, ncols, i+1)
im = ax.imshow(mosaic, **kwargs)
ax.set_title("Layer #{} called '{}' \nof type {}".format(layer_id, layer.name, layer.__class__.__name__))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
plt.colorbar(im, cax=cax)
ax.axis('off')
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
#fig.tight_layout()
return fig
def get_plot_axes(self, figure=None, ax_xy=None):
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
xmin, xmax, ymin, ymax, zmin, zmax = self.get_extent()
if figure is None and ax_xy is None:
figure = plt.figure()
if figure is None and ax_xy is not None:
figure = ax_xy.get_figure()
if ax_xy is None:
ax_xy = figure.add_subplot(111)
ratio = float(xmax - xmin) / (ymax - ymin)
plot_xz_size = ((zmax - zmin)/(xmax - xmin))*100
plot_yz_size = plot_xz_size / ratio
plot_cbar_size = 5 # percent
xz_size = '%f %%' % plot_xz_size
yz_size = '%f %%' % plot_yz_size
cb_size = '%f %%' % plot_cbar_size
# ax_xy
divider = make_axes_locatable(ax_xy)
plt.setp(ax_xy.get_xticklabels(), visible=False)
ax_xy.set_xlim(xmin, xmax)
ax_xy.set_ylim(ymin, ymax)
ax_xy.set_aspect('equal', 'datalim')
plt.setp(ax_xy.get_yticklabels(), rotation=90, fontsize=12)
# ax_yz
ax_yz = divider.append_axes(
'right', size=yz_size, pad=0.05, sharey=ax_xy)
plt.setp(ax_yz.get_yticklabels(), visible=False)
ax_yz.set_xlim(zmin, zmax)
ax_yz.set_ylim(ymin, ymax)
plt.setp(ax_yz.get_xticklabels(), rotation=90, fontsize=12)
plt.setp(ax_yz.get_yticklabels(), rotation=90, fontsize=12)
# ax_xz
ax_xz = divider.append_axes(
'bottom', size=xz_size, pad=0.05, sharex=ax_xy)
ax_xz.set_xlim(xmin, xmax)
ax_xz.set_ylim(zmax, zmin)
# color-bar
ax_cb = divider.append_axes('bottom', size=cb_size, pad=0.5)
return ax_xy, ax_xz, ax_yz, ax_cb
plot_cstc_overview.py 文件源码
项目:dragonboard_testbench
作者: cta-observatory
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def main(cstcfile, args):
st = pd.HDFStore(cstcfile)
keys = st.keys()[:-2] # ignore channel 7
name, ext = os.path.splitext(cstcfile)
with PdfPages(name + '.pdf') as pdf:
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
for i, n in enumerate(keys):
df = st[n]
m = df.groupby(['cell', 'sample']).mean()
s = df.groupby(['cell', 'sample']).std()
m2d = m['adc_counts'].values.reshape(-1, 40)
s2d = s['adc_counts'].values.reshape(-1, 40)
plots = {
'mean': {
'data': m2d,
'ax_id': 0,
'vmax': 15,
'vmin': -15,
'cmap': 'RdBu_r',
},
'std_dev': {
'data': s2d,
'ax_id': 1,
'vmax': 30,
'vmin': 0,
'cmap': 'viridis',
},
}
for plot_name, plot in plots.items():
ax = axes[plot['ax_id']]
ax.cla()
im = ax.imshow(
plot['data'],
cmap=plot['cmap'],
aspect='auto',
interpolation='nearest',
vmin=plot['vmin'],
vmax=plot['vmax'],
)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
cb = fig.colorbar(im, cax=cax)
cb.set_label(plot_name + ' adc count')
ax.set_xlabel('sample')
ax.set_ylabel('cell')
ax.set_title(n)
fig.tight_layout()
pdf.savefig(fig)