本文整理汇总了Python中matplotlib.colors.normalize函数的典型用法代码示例。如果您正苦于以下问题:Python normalize函数的具体用法?Python normalize怎么用?Python normalize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了normalize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_maps
def plot_maps(plot_params, anat_fn, anat_slice_def, fig_dir,
orientation=['axial','sagittal'], crop_extension=None,
plot_anat=True, plot_fontsize=25, fig_dpi=75):
ldata = []
for p in plot_params:
c = xndarray.load(p['fn']).sub_cuboid(**p['slice_def'])
c.set_orientation(orientation)
ldata.append(c.data)
c_anat = xndarray.load(anat_fn).sub_cuboid(**anat_slice_def)
c_anat.set_orientation(orientation)
resolution = c_anat.meta_data[1]['pixdim'][1:4]
slice_resolution = resolution[MRI4Daxes.index(orientation[0])], \
resolution[MRI4Daxes.index(orientation[1])]
all_data = np.array(ldata)
if 'prl' in plot_params[0]['fn']:
norm = normalize(all_data.min(), all_data.max()*1.05)
print 'norm:', (all_data.min(), all_data.max())
else:
norm = normalize(all_data.min(), all_data.max())
print 'norm:', (all_data.min(), all_data.max())
for data, plot_param in zip(all_data, plot_params):
fn = plot_param['fn']
plt.figure()
print 'fn:', fn
print '->', (data.min(), data.max())
if plot_anat:
anat_data = c_anat.data
else:
anat_data = None
plot_func_slice(data, anatomy=anat_data,
parcellation=plot_param.get('mask'),
func_cmap=cmap,
parcels_line_width=1., func_norm=norm,
resolution=slice_resolution,
crop_extension=crop_extension)
set_ticks_fontsize(plot_fontsize)
fig_fn = op.join(fig_dir, '%s.png' %op.splitext(op.basename(fn))[0])
output_fig_fn = plot_param.get('output_fig_fn', fig_fn)
print 'Save to: %s' %output_fig_fn
plt.savefig(output_fig_fn, dpi=fig_dpi)
autocrop(output_fig_fn)
return norm
示例2: __init__
def __init__( self, data, ax, prefs, *args, **kw ):
PlotBase.__init__( self, data, ax, prefs, *args, **kw )
if type( data ) == types.DictType:
self.gdata = GraphData( data )
elif type( data ) == types.InstanceType and data.__class__ == GraphData:
self.gdata = data
if self.prefs.has_key( 'span' ):
self.width = self.prefs['span']
else:
self.width = 1.0
if self.gdata.key_type == "time":
nKeys = self.gdata.getNumberOfKeys()
self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys
# Setup the colormapper to get the right colors
self.cmap = LinearSegmentedColormap( 'quality_colormap', cdict, 256 )
#self.cmap = cm.RdYlGn
self.norms = normalize( 0, 100 )
mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms )
mapper = cm.ScalarMappable( cmap = cm.RdYlGn, norm = self.norms )
def get_alpha( *args, **kw ):
return 1.0
mapper.get_alpha = get_alpha
self.mapper = mapper
示例3: colorify
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral):
""" Associate a color map to a quantity vector
Parameters
----------
data: sequence
values to index
vmin: float, optional
minimal value to index
vmax: float, optional
maximal value to index
cmap: colormap instance
colormap to use
Returns
-------
colors: sequence
color sequence corresponding to data
scalarMap: colormap
generated map
"""
import matplotlib.colors as colors
_vmin = vmin or min(data)
_vmax = vmax or max(data)
cNorm = colors.normalize(vmin=_vmin, vmax=_vmax)
scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap)
colors = map(scalarMap.to_rgba, data)
return colors, scalarMap
示例4: __init__
def __init__(self, cmapName="hsv", indexMin=0, indexMax=1):
"""
cmapName: color map name
indexMin, indexMax: mininal and maximal value of index used
used for normalization
"""
#self.cmap = cm.cmap_d[cmapName] # color map instance
self.cmap = cm.get_cmap(cmapName) # color map instance
self.norm = colors.normalize(indexMin, indexMax) # normalize instance
示例5: pproc
def pproc(filename, inArray, dir, max_value, padding, show_plot):
array = dirArray(inArray[0], dir)
#with open('1.dat', 'w') as f:
# for item in xArray:
# f.write(str(item))
mat = FilterMap(max_value, padding)
mat.filter(array)
#plt.imshow(mat.result)
maxV = max(map(max, mat.result))
minV = min(map(min, mat.result))
if (maxV**2 > minV**2): mv = np.sqrt(maxV**2)
else: mv = np.sqrt(minV**2)
print "max value of field: ", mv
print "half of max value of field: ", mv/2
# ['Spectral', 'summer', 'RdBu', 'Set1', 'Set2', 'Set3', 'brg_r', 'Dark2',
# 'hot', 'PuOr_r', 'afmhot_r', 'terrain_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r',
# 'gist_yarg_r', 'Dark2_r', 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r',
# 'gist_stern', 'gnuplot_r', 'cool_r', 'cool', 'gray', 'copper_r', 'Greens_r',
# 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow', 'RdYlBu_r', 'gist_heat_r',
# 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r', 'spring', 'terrain',
# 'YlOrRd_r', 'Set2_r', 'winter_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r',
# 'jet_r', 'RdPu_r', 'Purples_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'bwr',
# 'YlOrRd', 'Greens', 'PRGn', 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r',
# 'prism_r', 'Pastel2', 'Pastel1_r', 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r',
# 'gnuplot2_r', 'BuPu', 'YlGnBu_r', 'copper', 'gist_earth_r', 'Set3_r', 'OrRd',
# 'PuBu_r', 'ocean_r', 'brg', 'gnuplot2', 'jet', 'bone_r', 'gist_earth', 'Oranges',
# 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'Accent', 'BuPu_r', 'gist_gray',
# 'flag', 'seismic_r', 'RdBu_r', 'BrBG', 'Reds', 'BuGn_r', 'summer_r', 'GnBu_r', 'BrBG_r',
# 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r',
# 'pink', 'binary', 'winter', 'gnuplot', 'pink_r', 'prism', 'YlOrBr', 'rainbow_r', 'rainbow',
# 'PiYG_r', 'YlGn_r', 'Blues_r', 'YlOrBr_r', 'seismic', 'Purples', 'bwr_r', 'autumn_r',
# 'ocean', 'Set1_r', 'PuOr', 'PuBuGn', 'afmhot']
# norm = colors.normalize(-mv, mv)
# MUMAX
norm = colors.normalize(-1, 1)
# norm = colors.LogNorm()
# plt.matshow(mat.result, cmap='RdBu', norm=colors.LogNorm() )
plt.matshow(mat.result, norm=norm )
plt.colorbar(shrink=.8)
fig = plt.gcf()
if (show_plot==True): plt.show()
png_name = filename[0:(len(filename)-4)] + "_" "+.png"
a = re.split(r'\\', png_name)
addr = ""
for i in range(len(a)-1):
addr += a[i] +"\\"
print addr
addr += (dir+"_"+a[ len(a)-1 ])
print addr
#addr = nn
fig.savefig(addr, dpi=100)
plt.close()
示例6: make_mpl_image_properties
def make_mpl_image_properties(func_man):
""" Create a dictionary of matplotlib AxesImage color mapping
properties from the corresponding properties in an OverlayInterface
"""
from matplotlib.colors import normalize
props = dict()
props['cmap'] = func_man.colormap
props['interpolation'] = func_man.interpolation
props['alpha'] = func_man.alpha()
props['norm'] = normalize(*func_man.norm)
return props
示例7: colorify
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral):
""" Associate a color map to a quantity vector """
import matplotlib.colors as colors
_vmin = vmin or min(data)
_vmax = vmax or max(data)
cNorm = colors.normalize(vmin=_vmin, vmax=_vmax)
scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap)
colors = map(scalarMap.to_rgba, data)
return colors, scalarMap
示例8: __init__
def __init__(self, cmapName="hsv", indexMin=0, indexMax=1):
"""
cmapName: color map name
indexMin, indexMax: mininal and maximal value of index used
used for normalization
"""
self.cmap = cm.cmap_d[cmapName] # color map instance
self.norm = colors.normalize(indexMin, indexMax) # normalize instance
self.set_color(indexMin) # implicit setting of point color
示例9: _draw_features
def _draw_features(self, **kwargs):
xoffset = kwargs.get('xoffset',0)
for feat_numb, feat2draw in enumerate(self.features):
if feat2draw.color_by_cm:
if feat2draw.use_score_for_color:
feat2draw.cm_value = feat2draw.score
feat2draw.fc = self.cm(feat2draw.cm_value)
else:# color by feature number
if not feat2draw.cm_value:
self.norm = colors.normalize(1,len(self.features)+1,)
feat2draw.cm_value = feat_numb +1
feat2draw.fc = self.cm(self.norm(feat2draw.cm_value))
feat2draw.draw_feature()
feat2draw.draw_feat_name(xoffset = xoffset)
示例10: add_data
def add_data(self, data):
"""
Adiciona serie temporal para UFs [(UF,tempo,valor),...]
"""
vals = array([i[2] for i in data])
norm = normalize(vals.min(), vals.max())
for i, d in enumerate(data):
print i
pm = self.pmdict[d[0]]
#clone placemark to receive new data
pm_newtime = pm.cloneNode(1)
# Renaming placemark
on = pm_newtime.getElementsByTagName('name')[0]
nn = self.kmlDoc.createElement('name')
nn.appendChild(self.kmlDoc.createTextNode(d[0]+'-'+str(d[1])))
pm_newtime.replaceChild(nn, on)
nl = pm_newtime.childNodes
#extrude polygon
pol = pm_newtime.getElementsByTagName('Polygon')[0]
alt = self.kmlDoc.createElement('altitudeMode')
alt.appendChild(self.kmlDoc.createTextNode('relativeToGround'))
ex = self.kmlDoc.createElement('extrude')
ex.appendChild(self.kmlDoc.createTextNode('1'))
ts = self.kmlDoc.createElement('tessellate')
ts.appendChild(self.kmlDoc.createTextNode('1'))
pol.appendChild(alt)
pol.appendChild(ex)
pol.appendChild(ts)
lr = pm_newtime.getElementsByTagName('LinearRing')[0]
nlr = self.extrude_polygon(lr, d[2])
ob = pm_newtime.getElementsByTagName('outerBoundaryIs')[0]
# ob.replaceChild(nlr, lr)
ob.removeChild(lr)
ob.appendChild(nlr)
#set polygon style
col = rgb2hex(cm.Oranges(norm(d[2]))[:3])+'ff'
st = pm_newtime.getElementsByTagName('Style')[0] #style
nst = self.set_polygon_style(st, col)
pm_newtime.removeChild(st)
pm_newtime.appendChild(nst)
#add timestamp
ts = self.kmlDoc.createElement('TimeStamp')
w = self.kmlDoc.createElement('when')
w.appendChild(self.kmlDoc.createTextNode(str(d[1])))
ts.appendChild(w)
pm_newtime.appendChild(ts)
self.folder.appendChild(pm_newtime)
for pm in self.pmdict.itervalues():
self.folder.removeChild(pm)
示例11: plot_sensor_data
def plot_sensor_data(sensor, plot_type="grey", outfile="output.png"):
# Create canvas
print "Preparing the plot"
fig = plt.figure()
if (plot_type == "3d"):
ax = fig.add_subplot(111, projection='3d')
# Calculate 3d plot data: grid
xedges = np.arange(0, s.pixel_rows+1)
yedges = np.arange(0, s.pixel_columns+1)
elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.05, yedges[:-1]+0.05)
# Calculate starting x, y, z
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
# Areas of the bins, flatten the heights
dx = 0.9 * np.ones_like(zpos)
dy = dx.copy()
dz = np.array(s.data()).flatten()
print "Calculating colors..."
norm = colors.normalize(dz.min(), dz.max())
col = []
for i in dz:
col.append(cm.jet(norm(i)))
print "Now rendering image..."
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=col, zsort='average')
else:
ax = fig.add_subplot(111)
dz = np.array(s.data()).flatten()
cma = cm.jet
if (plot_type == "grey"):
cma = cm.Greys
cax = ax.imshow(s.data(), interpolation='nearest', cmap=cma)
cbar = fig.colorbar(cax, ticks=[dz.min(), (dz.max()+dz.min())/2, dz.max()], orientation='vertical')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar
ax.set_title('Sensor Data')
print "Saving image..."
plt.savefig(outfile, dpi=500)
print "All done!"
示例12: db_to_logs
def db_to_logs(ano):
"""
Extrai as decisoes do bancoe as salva em um arquivo no formato do Gource
"""
#Q = dbdec.execute("SELECT relator,processo,tipo,proc_classe,duracao, UF,data_dec, count(*) FROM decisao WHERE DATE_FORMAT(data_dec,'%Y%')="+"%s"%ano+" GROUP BY relator,tipo,proc_classe")
Q = dbdec.execute("SELECT relator,processo,tipo,proc_classe,duracao, UF,data_dec FROM decisao WHERE DATE_FORMAT(data_dec,'%Y%')="+"%s"%ano+" ORDER BY data_dec asc")
decs = Q.fetchall()
durations = [d[4] for d in decs]
cmap = cm.jet
norm = normalize(min(durations), max(durations)) #normalizing durations
with open('decisoes_%s.log'%ano, 'w') as f:
for d in decs:
c = rgb2hex(cmap(norm(d[4]))[:3]).strip('#')
path = "/%s/%s/%s/%s"%(d[5],d[2],d[3], d[1]) #/State/tipo/proc_classe/processo
l = "%s|%s|%s|%s|%s\n"%(int(time.mktime(d[6].timetuple())), d[0], 'A', path, c)
f.write(l)
示例13: histogram
def histogram(self):
self.ax.set_title('Histogram of Evidence Based Scheduling [ %d ]' % len(self.H))
self.ax.set_xlabel('Time (h)',fontstyle='italic')
self.ax.set_ylabel('Probability (%)',fontstyle='italic')
self.ax.set_ylim(0,110)
self.ax.grid(True)
self.ax.axvline(self.u, color='#90EE90', linestyle='dashed', lw=2)
self.H += self.mc.probes(1000)
n, bins, patches = self.ax.hist(self.H, bins=self.count , edgecolor='white', alpha=0.75)
nmax=n.max() # najwyższy słupek
# zmienna skala osi Y
self.ax.set_xticks([ round(i,2) for i in bins[::self.scale] ])
# self.ax.set_xticklabels(('a','b')) # tak można dodać label zamiast wartości
self.figure.autofmt_xdate() # pochyłe literki
# strzałka
if self.arrow:
pyplot.annotate('simple estimation', xy=(self.u, 90), xytext=(min(bins), 100),
arrowprops=dict(facecolor='blue', shrink=0.005))
if self.help == 1 :
pyplot.annotate('help (h)',
xy=(max(bins), 90),
xytext=((self.u+max(bins))/2, 90),
ha='left')
elif self.help == 2 :
pyplot.annotate('\n'.join(self.usage),
xy=(max(bins), 90),
xytext=((self.u+max(bins))/2, 60),
ha='left')
# normalizacja
for p in patches:
p.set_height((p.get_height() * 100.0 ) / nmax )
# tęcza
fracs = n.astype(float)/nmax
norm = colors.normalize(fracs.min(), fracs.max())
for f, p in zip(fracs, patches):
color = cm.jet(norm(f))
p.set_facecolor(color)
示例14: hist_com_difference_plot
def hist_com_difference_plot(filename,image_output,graph_title=''):
distance = []
for line in open(filename):
if line[0] == "#" or line[0] == "@": continue
line_content = line.split()
distance.append(float(line_content[1]))
fig = figure()
N,bins,patches = hist(distance,range(-30,30))
fracs = N.astype(float)/N.max()
norm = colors.normalize(fracs.min(), fracs.max())
for thisfrac, thispatch in zip(fracs, patches):
color = cm.jet(norm(thisfrac))
thispatch.set_facecolor(color)
xlabel('Z Distance between Protein and Bilayer centers')
ylabel('Frequency')
title(graph_title)
savefig(image_output)
示例15: plot_mod
def plot_mod(x, z, yvals, ylabel, ax, ind=0, cmap=pl.cm.rainbow,
printlabel=True):
""" Plot column-density-derived values yvals as a function of the
x values (NHI, nH or Z), showing variation of quantity z by
different coloured curves. ind is the index of the value used,
which isn't varied.
"""
# Want index order to be indtype, x, z. By default it's NHI, nH,
# Z. Otherwise it has to change...
if (x,z) == ('NHI','Z'):
yvals = np.swapaxes(yvals, 0, 1)
elif (x,z) == ('Z','NHI'):
yvals = np.swapaxes(yvals, 0, 1)
yvals = np.swapaxes(yvals, 1, 2)
elif (x,z) == ('nH','NHI'):
yvals = np.swapaxes(yvals, 0, 2)
elif (x,z) == ('NHI', 'nH'):
yvals = np.swapaxes(yvals, 0, 2)
yvals = np.swapaxes(yvals, 1, 2)
elif (x,z) == ('Z','nH'):
yvals = np.swapaxes(yvals, 1, 2)
norm = colors.normalize(M[z].min(), M[z].max())
label_indices = set((0, len(M[z])//2, len(M[z])-1))
for i in range(len(M[z])):
# spring, summer, autumn, winter are all good
c = cmap(norm(M[z][i]))
label = None
if i in label_indices:
label = labels[z] % M[z][i]
#ax.plot(M[x], yvals[ind,:,i], '-', lw=2.5, color='k')
ax.plot(M[x], yvals[ind,:,i], '-', lw=1.5, color=c, label=label)
val, = list(set(['nH','NHI','Z']).difference([x,z]))
if printlabel:
ax.set_title(labels[val] % M[val][ind], fontsize='medium')
ax.title.set_y(1.01)
ax.set_xlabel(xlabels[x], fontsize='small')
ax.set_ylabel(ylabel)
ax.minorticks_on()
ax.set_xlim(M[x][0]+1e-3, M[x][-1]-1e-3)