本文整理汇总了Python中matplotlib.cm.get_cmap函数的典型用法代码示例。如果您正苦于以下问题:Python get_cmap函数的具体用法?Python get_cmap怎么用?Python get_cmap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_cmap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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)
示例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)
示例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)
示例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
示例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)
示例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()
示例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()
示例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)
示例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()
示例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()
示例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)
示例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.)
示例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))]
示例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