本文整理汇总了Python中matplotlib.cm.get_cmap函数的典型用法代码示例。如果您正苦于以下问题:Python get_cmap函数的具体用法?Python get_cmap怎么用?Python get_cmap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_cmap函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plot
def plot (self, xres, yres, plain, spectra, nchan, freq, bw, tsamp, nsamps):
self.openPlot(xres, yres, plain)
tmin = 0
tmax = nsamps * tsamp
fmin = freq - (bw/2)
fmax = freq + (bw/2)
if numpy.amax(spectra) == numpy.amin(spectra):
spectra[0][0] = 1
if self.zap:
spectra[0,:] = 0
if self.log:
vmax = numpy.log(numpy.amax(spectra))
self.ax.imshow(spectra, extent=(tmin, tmax, fmin, fmax), aspect='auto',
origin='lower', interpolation='nearest', norm=LogNorm(vmin=0.0001,vmax=vmax),
cmap=cm.get_cmap('gray'))
else:
self.ax.imshow(spectra, extent=(tmin, tmax, fmin, fmax), aspect='auto',
origin='lower', interpolation='nearest',
cmap=cm.get_cmap('gray'))
self.closePlot()
开发者ID:ajameson,项目名称:spip,代码行数:26,代码来源:plotting.py
示例2: _create_palette
def _create_palette(self):
'''Create a palette based on Matplotlib colormap name
default number of color palette is 250.
it means 6 colors are possible to use for other purposes.
the last palette (255) is white and the second last (254) is black.
Modifies
--------
self.palette : numpy array (uint8)
'''
# test if given colormap name is in builtin or added colormaps
try:
cmap = cm.get_cmap(self.cmapName)
except:
self.logger.error('%s is not a valid colormap' % self.cmapName)
self.cmapName = self._cmapName
# get colormap by name
cmap = cm.get_cmap(self.cmapName)
# get colormap look-up
cmapLUT = np.uint8(cmap(range(self.numOfColor)) * 255)
# replace all last colors to black and...
lut = np.zeros((3, 256), 'uint8')
lut[:, :self.numOfColor] = cmapLUT.T[:3]
# ...and the most last color to white
lut[:, -1] = 255
# set palette to be used by PIL
self.palette = lut.T.flatten().astype(np.uint8)
开发者ID:WYC19910220,项目名称:nansat,代码行数:32,代码来源:figure.py
示例3: main
def main(months=None):
"""
Note: if you want to compare more than 2 simulations at the same time
make sure that the differences are plotted correctly
:param months:
"""
matplotlib.rc("font", size=20)
# List of simulations to compare
label_to_path = OrderedDict([
("(1) Without interflow", "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5"),
("(2) With interflow-a", "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl-intfl_ITFS.hdf5"),
# ("With interflow (b)",
# "/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl-intfl_ITFS_avoid_truncation1979-1989.hdf5")
])
nsims = len(label_to_path)
width_ratios = nsims * [1.0, ] + [0.05, ] + [1.3, 0.05]
gs = GridSpec(1, nsims + 3, width_ratios=width_ratios, wspace=0.25)
cdelta = 0.05
clevels = np.arange(-1.0, 1.0 + cdelta, cdelta)
cnorm = BoundaryNorm(clevels, len(clevels) - 1)
cmap = cm.get_cmap("RdBu_r", len(clevels) - 1)
start_year = 1980
end_year = 1989
keys = [k.replace(" ", "-") for k in label_to_path]
keys.extend([str(i) for i in (start_year, end_year)])
keys.append("-".join(str(m) for m in months))
img_path = "corr-SM-LH_{}_{}_{}-{}_{}.png".format(*keys)
fig = plt.figure()
assert isinstance(fig, Figure)
fig.set_figwidth(fig.get_figwidth() * 3)
im = None
sim_label_to_corr = OrderedDict()
for col, (sim_label, sim_path) in enumerate(label_to_path.items()):
ax = fig.add_subplot(gs[0, col])
im, corr = plot_for_simulation(axis=ax, sim_path=sim_path, cmap=cmap, cnorm=cnorm,
start_year=start_year, end_year=end_year, months=months)
ax.set_title(sim_label)
sim_label_to_corr[sim_label] = corr
plt.colorbar(im, cax=fig.add_subplot(gs[0, nsims]))
# plot differences in correlation
cdelta = 0.05
clevels = np.arange(-0.5, -cdelta, cdelta)
clevels = clevels.tolist() + [-c for c in reversed(clevels)]
cnorm = BoundaryNorm(clevels, len(clevels) - 1)
cmap = cm.get_cmap("RdBu_r", len(clevels) - 1)
im = plot_correlation_diff(sim_label_to_corr, file_for_basemap=list(label_to_path.values())[0],
ax=fig.add_subplot(gs[0, nsims + 1]), cnorm=cnorm, cmap=cmap)
plt.colorbar(im, cax=fig.add_subplot(gs[0, nsims + 2]))
# fig.tight_layout()
fig.savefig(img_path)
开发者ID:guziy,项目名称:RPN,代码行数:60,代码来源:compare_soil_moisture_latent_heat_correlations.py
示例4: main
def main():
get_file = lambda x: "cru_ts3.23.1901.2014.{0}.100mean.pkl".format(x)
tair_data = pickle.load(open(FILEPATH + get_file('tmp'), 'rb'))
rain_data = pickle.load(open(FILEPATH + get_file('pre'), 'rb'))
sav_patch = pickle.load(open(PATCHPATH, 'rb'))
fig = plt.figure(figsize=(10, 6), frameon=False)
fig.add_axes([0, 0, 1.0, 1.0])
n_plots = 2
grid = gridspec.GridSpec(n_plots, 1, hspace=0.3)
subaxs = [plt.subplot(grid[i]) for i in range(n_plots)]
# Mean Annual Temperature plot
make_map(subaxs[0], tair_data, sav_patch['clip'], \
cmap=get_cmap(MAPCOLOR), \
levels=np.arange(15, 35, 0.5), \
cticks=np.arange(15, 35, 2.5), \
title="Global Savanna Bioregion \\\\ Mean Annual Temperature (1901 to 2013)")
# Mean Annual Rainfall plot
make_map(subaxs[1], rain_data, sav_patch['clip'], \
cmap=get_cmap(MAPCOLOR), \
levels=np.logspace(1, 3, 100), \
cticks=[10, 50, 100, 200, 500, 1000], \
norm=SymLogNorm(linthresh=0.3, linscale=0.03), \
title="Global Savanna Bioregion \\\\ Mean Annual Precipitation (1901 - 2013)")
plt.savefig(SAVEPATH)
开发者ID:rhyswhitley,项目名称:spatial_plots,代码行数:32,代码来源:grid_spatial_plot.py
示例5: __plot_storage
def __plot_storage(prefix, show_cb=False, row=0, col=0, plot_deviations=True):
if plot_deviations:
clevs = [0, 1e3, 1e4, 1e5, 1.0e6, 1e7, 1e8, 1.0e9]
clevs = [-c for c in reversed(clevs)][:-1] + clevs
cmap = cm.get_cmap("bwr", len(clevs) - 1)
else:
clevs = [0, 1e3, 1e4, 1e5, 1.0e6, 1e7, 1e8, 1.0e9]
cmap = cm.get_cmap("YlGnBu", len(clevs) - 1)
norm = BoundaryNorm(boundaries=clevs, ncolors=len(clevs) - 1)
_storage = ds["{}_{}".format(prefix, storage_var_name)][:]
ax = fig.add_subplot(gs[row, col])
_storage = _storage.where(_storage > storage_lower_limit_m3)
_storage = maskoceans(lons2d_, lats2d, _storage)
_storage = np.ma.masked_where(np.isnan(_storage), _storage)
if plot_deviations:
cs = bmap.pcolormesh(xx, yy, _storage - bankfull_storage, norm=norm, cmap=cmap)
else:
cs = bmap.pcolormesh(xx, yy, _storage, norm=norm, cmap=cmap)
ext = "both" if plot_deviations else "max"
cb = bmap.colorbar(cs, location="bottom", format=FuncFormatter(__storage_cb_format_ticklabels), extend=ext)
cb.ax.set_visible(show_cb)
cb.ax.set_xlabel(r"${\rm m^3}$")
ax.set_title(prefix)
axes.append(ax)
return _storage
开发者ID:guziy,项目名称:RPN,代码行数:34,代码来源:calculate_flood_storage.py
示例6: cmap_discretize
def cmap_discretize(cmap, n_colors=10):
"""Return discretized colormap.
Parameters
----------
cmap : str or colormap object
Colormap to discretize.
n_colors : int
Number of discrete colors to divide `cmap` into.
Returns
----------
disc_cmap : LinearSegmentedColormap
Discretized colormap.
"""
try:
cmap = cm.get_cmap(cmap)
except:
cmap = cm.get_cmap(eval(cmap))
colors_i = np.concatenate((np.linspace(0, 1., n_colors), (0., 0., 0., 0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., n_colors + 1)
cdict = {}
for ki, key in enumerate(('red', 'green', 'blue')):
cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki])
for i in range(n_colors + 1)]
return mpl.colors.LinearSegmentedColormap(cmap.name + "_%d" % n_colors,
cdict, 1024)
开发者ID:UW-Hydro,项目名称:tonic,代码行数:29,代码来源:plot_utils.py
示例7: featurePosPlot
def featurePosPlot(featureList, name, k=1, save=None):
font = {'family' : 'monospace',
'weight' : 'normal',
'size' : '6'}
plt.rc('font', **font)
fig = plt.figure(k)
fig.suptitle(name)
ax = fig.add_subplot(221)
sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['mav'], s=1000, cmap=cm.get_cmap('binary'))
ax.set_title("mav")
plt.colorbar(sc, ticks = featureList['mav'])
ax.grid(True)
ax = fig.add_subplot(224)
sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['ni'], s=1000, cmap=cm.get_cmap('binary'))
ax.set_title("ni")
plt.colorbar(sc, ticks = featureList['ni'])
ax.grid(True)
ax = fig.add_subplot(222)
sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['rmsd'], s=1000, cmap=cm.get_cmap('binary'))
plt.colorbar(sc, ticks = featureList['rmsd'])
ax.set_title("rmsd")
ax.grid(True)
ax = fig.add_subplot(223)
sc = ax.scatter([2,2,3,3,3,2], [3,1,1,2,3,2], c=featureList['var'], s=1000, cmap=cm.get_cmap('binary'))
ax.set_title("var")
plt.colorbar(sc, ticks = featureList['var'])
ax.grid(True)
if save:
save.savefig(k)
else:
plt.show()
开发者ID:Yakisoba007,项目名称:PyTrigno,代码行数:33,代码来源:feature.py
示例8: __plot
def __plot(self, spectrum):
x, y, z = create_mesh(spectrum, True)
self.parent.clear_plots()
if self.settings.autoL:
vmin, vmax = self.barBase.get_clim()
else:
zExtent = self.extent.get_l()
vmin = zExtent[0]
vmax = zExtent[1]
if self.parent.settings.wireframe:
self.parent.plot = \
self.axes.plot_wireframe(x, y, z,
rstride=1, cstride=1,
linewidth=0.1,
cmap=cm.get_cmap(self.settings.colourMap),
gid='plot_line',
antialiased=True,
alpha=1)
else:
self.parent.plot = \
self.axes.plot_surface(x, y, z,
rstride=1, cstride=1,
vmin=vmin, vmax=vmax,
linewidth=0,
cmap=cm.get_cmap(self.settings.colourMap),
gid='plot_line',
antialiased=True,
alpha=1)
return self.extent.get_peak_flt()
开发者ID:kronoc,项目名称:RTLSDR-Scanner,代码行数:31,代码来源:plot_3d.py
示例9: showMask
def showMask(self, splot, mask):
if mask != None:
nr, nc = mask.shape
extent = [-0.5, nc-0.5, -0.5, nr-0.5]
if self.displayMaskFlag == self.MASK_SHOWN:
labels = _N.unique(mask)
for il, lab in enumerate(labels):
if lab != 0:
if self.maskCm!=None : cm = self.maskCm[lab]
else : cm = get_cmap('binary')
splot.contour((mask==lab).astype(int), 1,
cmap=cm, linewidths=2., extent=extent,alpha=.7)
#cmap=cm, linewidths=1.5, extent=extent,alpha=.7)
if self.displayMaskFlag == self.MASK_ONLY:
if self.maskLabel == 0:
labels = _N.unique(mask)
for il, lab in enumerate(labels):
if lab != 0:
if self.maskCm != None:
cm = self.maskCm[lab]
else:
cm = get_cmap('binary')
ml = (mask==lab).astype(int)
print 'contouf of mask label %d -> %d pos' \
%(lab, ml.sum())
splot.contourf(ml, 1,
cmap=cm, linewidths=1., extent=extent)
elif (mask==self.maskLabel).sum() > 0:
if self.maskCm != None:
cm = self.maskCm[_N.where(mask==self.maskLabel)[0]]
else:
cm = get_cmap('binary')
ax.contourf((mask==self.maskLabel).astype(int), 1,
cmap=cm, linewidths=1.5, extent=extent)
开发者ID:pmesejo,项目名称:pyhrf,代码行数:35,代码来源:mplwidget.py
示例10: plotKernel
def plotKernel(xRange, yRange, kernel, label):
fig = plt.figure()
plt.subplot(1,2,1)
# adding the Contour lines with labels
kernelMax = np.max(kernel)
kernelMin = np.min(kernel)
kernelValueThreshold = 10**-1
if np.abs(kernelMax - kernelMin) < kernelValueThreshold:
print "kernel value range is < " + str(kernelValueThreshold) + ", therefore image will not contains contours"
else:
contourIncrement = np.round(np.abs((kernelMax - kernelMin)) * 0.1, 2)
contourRange = np.arange(np.min(kernel), np.max(kernel) , contourIncrement )
cset = contour(kernel,contourRange, linewidths=2,cmap=cm.get_cmap('set2'))
plt.clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
# latex fashion title
# title('$z=3*e^{-(x^2+y^2)}$')
title(label)
plt.imshow(kernel,cmap=cm.get_cmap('gray')) # drawing the function
ax = fig.add_subplot(1, 2, 2, projection='3d')
surf = ax.plot_surface(xRange, yRange, kernel, rstride=1, cstride=1,
cmap=cm.get_cmap('RdBu'),linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
plt.show()
开发者ID:RockStarCoders,项目名称:alienMarkovNetworks,代码行数:32,代码来源:DataVisualisation.py
示例11: create_2_plots_v
def create_2_plots_v(mic1, mic2, title1, title2, xlabel1, ylabel1, xlabel2, ylabel2, colormap):
fig, axes = plt.subplots(2, sharex=True)
mic_array = array(mic1)
dimensions = mic_array.shape
nx = dimensions[0]
ny = dimensions[1]
axes[0].imshow(mic1, extent=(0, nx, ny, 0),cmap=cm.get_cmap(colormap))
axes[0].set_title(title1)
axes[0].set_xlabel(xlabel1)
axes[0].set_ylabel(ylabel1)
axes[0].set_ylim([0,ny])
mic_array = array(mic2)
dimensions = mic_array.shape
nx = dimensions[0]
ny = dimensions[1]
print(nx, ny)
axes[1].imshow(mic2, extent=(0, nx, ny, 0),cmap=cm.get_cmap(colormap))
axes[1].set_title(title2)
axes[1].set_xlabel(xlabel2)
axes[1].set_ylabel(ylabel2)
axes[1].set_ylim([0,ny])
plt.axis('tight')
plt.autoscale(enable=True, axis='y', tight=True)
plt.show()
开发者ID:yallapragada,项目名称:mic_2p,代码行数:27,代码来源:plots_from_csv.py
示例12: save_seg_plot
def save_seg_plot(outfile_path, title_str1, title_str2,
ref_intervals, ref_labels, est_intervals, est_labels,
cmap='Accent'):
fig = plt.figure(figsize=(9, 3))
ulabel, invind = np.unique(ref_labels, return_inverse=True)
norm = mpl.colors.Normalize(vmin=np.min(invind), vmax=np.max(invind))
cmap = cm.get_cmap(cmap)
m = cm.ScalarMappable(norm=norm, cmap=cmap)
plt.subplot(211)
seg = [interval[0] for interval in ref_intervals[1:]]
plt.vlines(seg, 0, 1, linewidth=1)
for interval, i in zip(ref_intervals, invind):
plt.fill_between([interval[0], interval[1]], 0, 1, color=m.to_rgba(i))
plt.title('Ground truth segmentation - ' + title_str1)
plt.xlim(0, ref_intervals[-1][1])
plt.yticks([])
plt.xticks([])
ax = fig.add_subplot(212)
ulabel, invind = np.unique(est_labels, return_inverse=True)
norm = mpl.colors.Normalize(vmin=np.min(invind), vmax=np.max(invind))
cmap = cm.get_cmap(cmap)
m = cm.ScalarMappable(norm=norm, cmap=cmap)
seg = [interval[0] for interval in est_intervals[1:]]
plt.vlines(seg, 0, 1, linewidth=1)
for interval, i in zip(est_intervals, invind):
plt.fill_between([interval[0], interval[1]], 0, 1, color=m.to_rgba(i))
plt.title('Detected segmentation - ' + title_str2)
plt.xlim(0, est_intervals[-1][1])
plt.yticks([])
plt.xticks([])
plt.tight_layout()
plt.savefig(outfile_path)
开发者ID:wangsix,项目名称:segment,代码行数:35,代码来源:segment.py
示例13: _plot_radiation_pattern_quiver
def _plot_radiation_pattern_quiver(ax3d, ned_mt, type):
"""
Private routine that plots the wave farfield into an
:class:`~mpl_toolkits.mplot3d.axes3d.Axes3D` object
:type ax3d: :class:`mpl_toolkits.mplot3d.axes3d.Axes3D`
:param ax3d: matplotlib Axes3D object
:param ned_mt: the 6 comp moment tensor in NED orientation
:type type: str
:param type: 'P' or 'S' (P or S wave).
"""
import matplotlib.pyplot as plt
if MATPLOTLIB_VERSION < [1, 4]:
msg = ("Matplotlib 3D quiver plot needs matplotlib version >= 1.4.")
raise ImportError(msg)
type = type.upper()
if type not in ("P", "S"):
msg = ("type must be 'P' or 'S'")
raise ValueError(msg)
is_p_wave = type == "P"
# precompute even spherical grid and directional cosine array
points = _equalarea_spherical_grid(nlat=14)
if is_p_wave:
# get radiation pattern
disp = farfield(ned_mt, points, type="P")
# normalized magnitude:
magn = np.sum(disp * points, axis=0)
magn /= np.max(np.abs(magn))
cmap = get_cmap('bwr')
else:
# get radiation pattern
disp = farfield(ned_mt, points, type="S")
# normalized magnitude (positive only):
magn = np.sqrt(np.sum(disp * disp, axis=0))
magn /= np.max(np.abs(magn))
cmap = get_cmap('Greens')
# plot
# there is a mlab3d bug that quiver vector colors and lengths
# can only be changed if we plot each arrow independently
for loc, vec, mag in zip(points.T, disp.T, magn.T):
norm = plt.Normalize(-1., 1.)
color = cmap(norm(mag))
if is_p_wave:
loc *= (1. + mag / 2.)
length = abs(mag) / 2.0
else:
length = abs(mag) / 5.0
ax3d.quiver(loc[0], loc[1], loc[2], vec[0], vec[1], vec[2],
length=length, color=color)
ax3d.set(xlim=(-1.5, 1.5), ylim=(-1.5, 1.5), zlim=(-1.5, 1.5),
xticks=[-1, 1], yticks=[-1, 1], zticks=[-1, 1],
xticklabels=['South', 'North'],
yticklabels=['West', 'East'],
zticklabels=['Up', 'Down'],
title='{} wave farfield'.format(type))
ax3d.view_init(elev=-110., azim=0.)
开发者ID:junlysky,项目名称:obspy,代码行数:60,代码来源:source.py
示例14: mplcmap_to_palette
def mplcmap_to_palette(cmap, ncolors=None, categorical=False):
"""
Converts a matplotlib colormap to palette of RGB hex strings."
"""
from matplotlib.colors import Colormap, ListedColormap
ncolors = ncolors or 256
if not isinstance(cmap, Colormap):
import matplotlib.cm as cm
# Alias bokeh Category cmaps with mpl tab cmaps
if cmap.startswith('Category'):
cmap = cmap.replace('Category', 'tab')
try:
cmap = cm.get_cmap(cmap)
except:
cmap = cm.get_cmap(cmap.lower())
if isinstance(cmap, ListedColormap):
if categorical:
palette = [rgb2hex(cmap.colors[i%cmap.N]) for i in range(ncolors)]
return palette
elif cmap.N > ncolors:
palette = [rgb2hex(c) for c in cmap(np.arange(cmap.N))]
if len(palette) != ncolors:
palette = [palette[int(v)] for v in np.linspace(0, len(palette)-1, ncolors)]
return palette
return [rgb2hex(c) for c in cmap(np.linspace(0, 1, ncolors))]
开发者ID:ioam,项目名称:holoviews,代码行数:26,代码来源:util.py
示例15: ChangePlotType
def ChangePlotType(self, event):
self.figure.clear()
# Create an image plot
if event.GetId() == 100:
self.subplot = self.figure.add_subplot(111)
self.plot = self.subplot.imshow(self.z_values, cmap=cm.get_cmap('gnuplot2'), norm=None, aspect='equal',
interpolation=None, alpha=None, vmin=self.minValue, vmax=self.maxValue,
origin='lower')
self.plot_type = constants.IMAGE
# Create a 3D wire plot
if event.GetId() == 101:
self.subplot = self.figure.add_subplot(111, projection='3d')
self.plot = self.subplot.plot_wireframe(self.x_values, self.y_values, self.z_values)
self.plot_type = constants.WIREFRAME
# Create a 3D surface plt
if event.GetId() == 102:
self.subplot = self.figure.add_subplot(111, projection='3d')
self.plot = self.subplot.plot_surface(self.x_values, self.y_values, self.z_values, rstride=1, cstride=1,
cmap=cm.get_cmap('cool'), linewidth=0, antialiased=False)
self.plot_type = constants.SURFACE
if event.GetId() == 103:
self.subplot = self.figure.add_subplot(111)
dataCopy = self.z_values.copy(order='K')
x_values = np.arange(0, dataCopy.size)
self.subplot.plot(x_values, dataCopy.flatten('A'))
self.plot_type = constants.TWOD_PLOT
self.canvas.draw()
return
开发者ID:roehrig,项目名称:XrayDiffractionDataTool,代码行数:35,代码来源:PlotFrame3D.py
示例16: plotprop
def plotprop(ax,d,xvar='npart',yvar='time',sclfact=None,tunit='s',
nlim={},**exkw):
"""Plot time vs. npart for processor number"""
from matplotlib import colors,cm
syms=['.','x','^','s']
lins=['-',':',';','.']
if xvar=='npart': nvar='nproc'
elif xvar=='nproc': nvar='npart'
else: raise Exception('Invalid x variable: {}'.format(xvar))
nlist=set(d[nvar])
if nvar=='npart': cmap=cm.get_cmap('cool')
elif nvar=='nproc': cmap=cm.get_cmap('cool')
lab=exkw.get('lab','')
lin=exkw.get('lin',lins[0])
sym=exkw.get('sym',syms[0])
p=[]
for i,n in enumerate(sorted(nlist)):
# Get x data and label
idx=(d[nvar]==n)
x=d[xvar][idx]
xlab=xvar.title()
if nvar=='npart': ilab=lab+'log{} = {:3.2f}'.format(nvar.title(),np.log10(n))
elif nvar=='nproc': ilab=lab+'{} = {}'.format(nvar.title(),n)
else: raise Exception('Unsupported nvar: {}'.format(nvar))
if xvar=='npart': xscl='log'
elif xvar=='nproc': xscl='linear'
else: raise Exception('Unsupported xvar: {}'.format(xvar))
# Get y data and label
if yvar=='time':
y=d['time' ][idx]
if sclfact=='npart':
y/=d['npart'][idx]
elif isinstance(sclfact,(float,int,np.ndarray)):
y*=sclfact
ylab='Time ({})'.format(tunit)
yscl='log'
elif yvar=='overhead':
y=d['To' ][idx]
ylab='Overhead ({})'.format(tunit)
yscl='log'
elif yvar=='speedup':
y=d['S' ][idx]
ylab='Speedup'
yscl=None
else: raise Exception('Invalid variable: {}'.format(yvar))
# Sort by increasing x
idxsort=np.argsort(x)
x=x[idxsort]
y=y[idxsort]
# Add properties to list
nlim.setdefault(xvar,(min(x),max(x)))
nlim.setdefault(nvar,(min(nlist),max(nlist)))
if nvar=='npart': norm=colors.LogNorm(*nlim[nvar])
elif nvar=='nproc': norm=colors.Normalize(*nlim[nvar])
else: raise Exception('Unsupported nvar: {}'.format(nvar))
clr=cmap(norm(n))
p.append({'xvar':xvar,'x':x,'xlab':xlab,'xlim':nlim[xvar],'xscl':xscl,
'yvar':yvar,'y':y,'ylab':ylab,'ylim':None ,'yscl':yscl,
'ax':ax,'style':lin,'marker':sym,'color':clr,'label':ilab})
return p
开发者ID:cfh5058,项目名称:mmlpy,代码行数:60,代码来源:tests.py
示例17: mapPerPeriod
def mapPerPeriod(aodperDegree, lats, longs, title, savefile, cmapname,minv=0,maxv=0):
# Make plot with vertical (default) colorbar
fig, ax = plt.subplots()
data = aodperDegree
datafile = cbook.get_sample_data('C:/Users/alex/marspython/aerosol/gr.png')
img = imread(datafile)
ax.imshow(img, zorder=1, alpha=0.3,
extent=[float(min(longs))-0.5, float(max(longs))+0.5, float(min(lats)) - 0.5, float(max(lats))+0.5])
if minv<>0 or maxv<>0 :
cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname),
extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))],
vmin=minv,vmax=maxv)
else:
cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname),
extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))])
ax.set_title(title)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
#cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
cbar = fig.colorbar(cax)
#cbar.ax.set_yticklabels(['< -1', '0', '> 1']) # vertically oriented colorbar
pylab.savefig(savefile + ".png")
开发者ID:tomasalex,项目名称:aerosol,代码行数:26,代码来源:plots.py
示例18: update_plot
def update_plot():
rf_scale = rf_slider.get_value()
n_scale = needle_slider.get_value()
g_scale = ground_slider.get_value()
f.clear()
a = f.add_subplot(211)
cmap = cm.get_cmap('spectral', 100)
im = rf_scale**2*pseudoz + n_scale*needlez + g_scale*groundz
implot = a.imshow( im, interpolation='nearest', cmap=cmap )
f.colorbar(implot)
m = np.mean( im )
s = np.std( im )
implot.set_clim(m-s, m+s)
a = f.add_subplot(212)
cmap = cm.get_cmap('spectral', 100)
im = rf_scale**2*pseudox + n_scale*needlex + g_scale*groundx
implot = a.imshow( im, interpolation='nearest', cmap=cmap )
f.colorbar(implot)
m = np.mean( im )
s = np.std( im )
implot.set_clim(0., m+0.1*s)
canvas.draw()
开发者ID:TomaszSakrejda,项目名称:musiqcWashington,代码行数:29,代码来源:test.py
示例19: getColorMap
def getColorMap(self):
if (COLOR_CHOICES[self.colorMap.get()] is 'other'):
cmap = cm.get_cmap(self.otherColorMap.get())
else:
cmap = cm.get_cmap(COLOR_CHOICES[self.colorMap.get()])
if cmap is None:
cmap = cm.jet
return cmap
开发者ID:I2PC,项目名称:scipion,代码行数:8,代码来源:viewer_resolution_monogenic_signal.py
示例20: mh_colors
def mh_colors(number):
if number <= 8:
colors = [cm.get_cmap('Set1')(1. * i / 8.0)
for i in range(9)]
else:
colors = [cm.get_cmap('gist_rainbow')(1. * i / (number - 1))
for i in range(number)]
return colors
开发者ID:mdsmith,项目名称:pbinternal2,代码行数:8,代码来源:Graphs.py
注:本文中的matplotlib.cm.get_cmap函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论