本文整理汇总了Python中matplotlib.colors.normalize函数的典型用法代码示例。如果您正苦于以下问题:Python normalize函数的具体用法?Python normalize怎么用?Python normalize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了normalize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:ainafp,项目名称:pyhrf,代码行数:50,代码来源:real_data_jde_rfir_glm.py
示例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
开发者ID:sbel,项目名称:bes3-jinr,代码行数:25,代码来源:QualityMapGraph.py
示例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
开发者ID:philrosenfield,项目名称:ResolvedStellarPops,代码行数:34,代码来源:plotting.py
示例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
开发者ID:gizela,项目名称:gizela,代码行数:10,代码来源:ColorMap.py
示例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()
开发者ID:pgru,项目名称:scripts,代码行数:55,代码来源:process_mumax.py
示例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
开发者ID:cindeem,项目名称:xipy,代码行数:11,代码来源:interface.py
示例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
开发者ID:mfouesneau,项目名称:faststats,代码行数:11,代码来源:figrc.py
示例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
开发者ID:gizela,项目名称:gizela,代码行数:11,代码来源:PointStyleColorMap.py
示例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)
开发者ID:apierleoni,项目名称:BioGraPy,代码行数:14,代码来源:tracks.py
示例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)
开发者ID:Ralpbezerra,项目名称:Supremo,代码行数:50,代码来源:kmlgen.py
示例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!"
开发者ID:ruphy,项目名称:esame-lab2,代码行数:48,代码来源:program.py
示例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)
开发者ID:Ralpbezerra,项目名称:Supremo,代码行数:16,代码来源:gourceviz.py
示例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)
开发者ID:borzole,项目名称:borzole,代码行数:45,代码来源:ebs.py
示例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)
开发者ID:hallba,项目名称:Sidekick,代码行数:19,代码来源:AutomatedPlot.py
示例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)
开发者ID:nhmc,项目名称:H2,代码行数:42,代码来源:cloudy_plot.py
示例16: hist_tilt_data_plot
def hist_tilt_data_plot(filename,image_output,graph_title='',modifier=0.,binwidth=5):
tilt = []
for line in open(filename):
if line[0] == "#" or line[0] == "@": continue
line_content = line.split()
if float(line_content[1]) <= 90: tilt.append(float(line_content[1]))
else: tilt.append(180 - float(line_content[1]))
if modifier != 0:
tilt = [modifier-angle for angle in tilt]
fig = figure()
N,bins,patches = hist(tilt,range(0,90,binwidth))
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('Tilt angle (degrees)')
ylabel('Frequency')
title(graph_title)
savefig(image_output)
开发者ID:hallba,项目名称:Sidekick,代码行数:21,代码来源:AutomatedPlot.py
示例17: _plot
def _plot(map):
global axis
mpl.rcParams['xtick.labelsize'] = 'medium'
mpl.rcParams['ytick.labelsize'] = 'medium'
mpl.rcParams['axes.grid'] = False
mpl.rcParams['figure.subplot.left'] = 0.06
mpl.rcParams['figure.subplot.right'] = 0.97
mpl.rcParams['figure.subplot.top'] = 0.9
mpl.rcParams['figure.subplot.bottom'] = 0.1
mpl.rcParams['axes.labelsize'] = 'medium'
mpl.rcParams['ytick.major.pad'] = 4
mpl.rcParams['xtick.major.pad'] = 4
fig = plt.figure(figsize=(16, 9))
axis = plt.gca()
fig.canvas.set_window_title('Contacts Histogram')
fig.canvas.mpl_connect('button_press_event', _onpick)
bar_heights = np.array(map.values()).astype(float)
bar_positions = np.array(map.keys())
bar_rectangles = plt.bar(bar_positions, bar_heights, width=1.0, linewidth=0)
plt.xlim(bar_positions.min(), bar_positions.max())
plt.ylim(0, bar_heights.max()+1)
plt.title('Contacts Histogram ' + '(cutoff distance = ' + str(distance_cutoff) + ur' \u00c5)' + '\n\n')
plt.xlabel('\nResidue Index')
plt.ylabel('Count\n')
# Set Colors of the bar
fractions = bar_heights/bar_heights.max()
normalized_colors = colors.normalize(fractions.min(), fractions.max())
count = 0
for rect in bar_rectangles:
c = cm.jet(normalized_colors(fractions[count]))
rect.set_facecolor(c)
count = count + 1
ax_text = plt.axes([0.81, -0.02, 0.13, 0.075], frameon=False)
Button(ax_text, 'Click to select and highlight the residue in PyMol...', color=(0.33,0.33,0.33))
fig.show()
# This dummy image and drawing it on the canvas is neccessary step to give back CGContextRef to the main window. Otherwise the buttons on main contact map window stops responding.
progressbar.ax.set_visible(False)
dummy_img = Image.new('RGBA',(x_img_length,y_img_length),(0,0,0,0))
glob_ax.imshow(dummy_img)
glob_ax.figure.canvas.draw()
开发者ID:emptyewer,项目名称:CMPyMOL,代码行数:40,代码来源:CMPyMOL1.0b.py
示例18: 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
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()
开发者ID:pgru,项目名称:scripts,代码行数:36,代码来源:holes_mod_summation.py
示例19: xrange
for ind_rate in xrange(len(X_IDX)):
for ind_strength in xrange(len(Y_IDX)):
tmp_mps = IDX[to1d(ind_rate, ind_strength, len(X_IDX))][2]
Z_IDX[0][ind_rate][ind_strength] = tmp_mps[0]
Z_IDX[1][ind_rate][ind_strength] = tmp_mps[1]
Z_IDX[2][ind_rate][ind_strength] = tmp_mps['whole']
tmp_sts = IDX[to1d(ind_rate, ind_strength, len(X_IDX))][3]
Z_IDX[3][ind_rate][ind_strength] = tmp_sts[0]
Z_IDX[4][ind_rate][ind_strength] = tmp_sts[1]
Z_IDX[5][ind_rate][ind_strength] = tmp_sts['whole']
# MPS plotting
MPS_FIG, MPS_AXS = plt.subplots(1, 3, figsize=(9, 3))
MPS_MIN_MAX = get_all_min_max([Z_IDX[i] for i in xrange(3)])
MPS_NORM = colors.normalize(MPS_MIN_MAX[0], MPS_MIN_MAX[1])
plot_run(MPS_FIG, "MPS", MPS_AXS, Z_IDX, range(3), MPS_NORM, IMSHOW_EXTENT)
# STS plotting
STS_FIG, STS_AXS = plt.subplots(1, 3, figsize=(9, 3))
STS_MIN_MAX = get_all_min_max([Z_IDX[i] for i in xrange(3, 6)])
STS_NORM = colors.normalize(STS_MIN_MAX[0], STS_MIN_MAX[1])
plot_run(STS_FIG, "STS", STS_AXS, Z_IDX, range(3, 6), STS_NORM, IMSHOW_EXTENT)
"""
FFT MAX
"""
FFT_ATTRS = (('paramset', '_v_attrs', 'Common', 'inter_conn_rate', 0, 1),
('paramset', '_v_attrs', 'Common', 'inter_conn_strength', 0, 1),
开发者ID:neuro-lyon,项目名称:multiglom-model,代码行数:31,代码来源:analysis_bigrun.py
示例20: streamplot
def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
minlength=0.1, transform=None):
"""Draws streamlines of a vector flow.
*x*, *y* : 1d arrays
an *evenly spaced* grid.
*u*, *v* : 2d arrays
x and y-velocities. Number of rows should match length of y, and
the number of columns should match x.
*density* : float or 2-tuple
Controls the closeness of streamlines. When `density = 1`, the domain
is divided into a 25x25 grid---*density* linearly scales this grid.
Each cell in the grid can have, at most, one traversing streamline.
For different densities in each direction, use [density_x, density_y].
*linewidth* : numeric or 2d array
vary linewidth when given a 2d array with the same shape as velocities.
*color* : matplotlib color code, or 2d array
Streamline color. When given an array with the same shape as
velocities, *color* values are converted to colors using *cmap*.
*cmap* : :class:`~matplotlib.colors.Colormap`
Colormap used to plot streamlines and arrows. Only necessary when using
an array input for *color*.
*norm* : :class:`~matplotlib.colors.Normalize`
Normalize object used to scale luminance data to 0, 1. If None, stretch
(min, max) to (0, 1). Only necessary when *color* is an array.
*arrowsize* : float
Factor scale arrow size.
*arrowstyle* : str
Arrow style specification.
See :class:`~matplotlib.patches.FancyArrowPatch`.
*minlength* : float
Minimum length of streamline in axes coordinates.
Returns
-------
*stream_container* : StreamplotSet
Container object with attributes
lines : `matplotlib.collections.LineCollection` of streamlines
arrows : collection of `matplotlib.patches.FancyArrowPatch` objects
repesenting arrows half-way along stream lines.
This container will probably change in the future to allow changes to
the colormap, alpha, etc. for both lines and arrows, but these changes
should be backward compatible.
"""
grid = Grid(x, y)
mask = StreamMask(density)
dmap = DomainMap(grid, mask)
if color is None:
color = axes._get_lines.color_cycle.next()
if linewidth is None:
linewidth = matplotlib.rcParams['lines.linewidth']
line_kw = {}
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10*arrowsize)
use_multicolor_lines = isinstance(color, np.ndarray)
if use_multicolor_lines:
assert color.shape == grid.shape
line_colors = []
else:
line_kw['color'] = color
arrow_kw['color'] = color
if isinstance(linewidth, np.ndarray):
assert linewidth.shape == grid.shape
line_kw['linewidth'] = []
else:
line_kw['linewidth'] = linewidth
arrow_kw['linewidth'] = linewidth
## Sanity checks.
assert u.shape == grid.shape
assert v.shape == grid.shape
if np.any(np.isnan(u)):
u = np.ma.array(u, mask=np.isnan(u))
if np.any(np.isnan(v)):
v = np.ma.array(v, mask=np.isnan(v))
integrate = get_integrator(u, v, dmap, minlength)
trajectories = []
for xm, ym in _gen_starting_points(mask.shape):
if mask[ym, xm] == 0:
xg, yg = dmap.mask2grid(xm, ym)
t = integrate(xg, yg)
if t != None:
trajectories.append(t)
if use_multicolor_lines:
if norm is None:
norm = mcolors.normalize(color.min(), color.max())
if cmap is None:
cmap = cm.get_cmap(matplotlib.rcParams['image.cmap'])
else:
cmap = cm.get_cmap(cmap)
#.........这里部分代码省略.........
开发者ID:andreas-h,项目名称:matplotlib,代码行数:101,代码来源:streamplot.py
注:本文中的matplotlib.colors.normalize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论