本文整理汇总了Python中matplotlib.cm.ScalarMappable方法的典型用法代码示例。如果您正苦于以下问题:Python cm.ScalarMappable方法的具体用法?Python cm.ScalarMappable怎么用?Python cm.ScalarMappable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.cm
的用法示例。
在下文中一共展示了cm.ScalarMappable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def __init__(self, fig,
cmap=None,
norm=None,
offsetx=0,
offsety=0,
origin=None,
**kwargs
):
"""
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
kwargs are an optional list of Artist keyword args
"""
martist.Artist.__init__(self)
cm.ScalarMappable.__init__(self, norm, cmap)
if origin is None:
origin = rcParams['image.origin']
self.origin = origin
self.figure = fig
self.ox = offsetx
self.oy = offsety
self.update(kwargs)
self.magnification = 1.0
示例2: write_cmap
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def write_cmap(outname, vals, scalarMap):
"""Write external cpt colormap file based on matplotlib colormap.
Parameters
----------
outname : str
name of output file (e.g. amplitude-cog.cpt)
vals : float
values to be mapped to ncolors
scalarMap: ScalarMappable
mapping between array value and colormap value between 0 and 1
"""
with open(outname, "w") as fid:
for val in vals:
cval = scalarMap.to_rgba(val)
fid.write(
"{0} {1} {2} {3} \n".format(
val, # value
int(cval[0] * 255), # R
int(cval[1] * 255), # G
int(cval[2] * 255),
)
) # B
fid.write("nv 0 0 0 0 \n") # nodata alpha transparency
示例3: make_coherence_cmap
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def make_coherence_cmap(
mapname="inferno", vmin=1e-5, vmax=1, ncolors=64, outname="coherence-cog.cpt"
):
"""Write default colormap (coherence-cog.cpt) for isce coherence images.
Parameters
----------
mapname : str
matplotlib colormap name
vmin : float
data value mapped to lower end of colormap
vmax : float
data value mapped to upper end of colormap
ncolors : int
number of discrete mapped values between vmin and vmax
"""
cmap = plt.get_cmap(mapname)
cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
write_cmap(outname, vals, scalarMap)
return outname
示例4: spy
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', hold=None, **kwargs):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
if hold is not None:
ax.hold(hold)
try:
ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
draw_if_interactive()
finally:
ax.hold(washold)
if isinstance(ret, cm.ScalarMappable):
sci(ret)
return ret
################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
示例5: colorbar
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def colorbar(mappable, cax=None, ax=None, **kw):
"""
Create a colorbar for a ScalarMappable instance.
Documentation for the pylab thin wrapper:
%(colorbar_doc)s
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
if cax is None:
cax, kw = make_axes(ax, **kw)
cax.hold(True)
cb = Colorbar(cax, mappable, **kw)
def on_changed(m):
cb.set_cmap(m.get_cmap())
cb.set_clim(m.get_clim())
cb.update_bruteforce(m)
cbid = mappable.callbacksSM.connect('changed', on_changed)
mappable.colorbar = cb
ax.figure.sca(ax)
return cb
示例6: graph_colors
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def graph_colors(nx_graph, vmin=0, vmax=7):
cnorm = mcol.Normalize(vmin=vmin, vmax=vmax)
cpick = cm.ScalarMappable(norm=cnorm, cmap='viridis')
cpick.set_array([])
val_map = {}
for k, v in nx.get_node_attributes(nx_graph, 'attr_name').items():
val_map[k] = cpick.to_rgba(v)
colors = []
for node in nx_graph.nodes():
colors.append(val_map[node])
return colors
##############################################################################
# Generate data
# -------------
#%% circular dataset
# We build a dataset of noisy circular graphs.
# Noise is added on the structures by random connections and on the features by gaussian noise.
示例7: changed
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def changed(self):
tcolors = [(tuple(rgba),)
for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
self.tcolors = tcolors
hatches = self.hatches * len(tcolors)
for color, hatch, collection in zip(tcolors, hatches,
self.collections):
if self.filled:
collection.set_facecolor(color)
# update the collection's hatch (may be None)
collection.set_hatch(hatch)
else:
collection.set_color(color)
for label, cv in zip(self.labelTexts, self.labelCValues):
label.set_alpha(self.alpha)
label.set_color(self.labelMappable.to_rgba(cv))
# add label colors
cm.ScalarMappable.changed(self)
示例8: colorbar
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def colorbar(mappable, cax=None, ax=None, **kw):
"""
Create a colorbar for a ScalarMappable instance.
Documentation for the pyplot thin wrapper:
%s
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
if cax is None:
cax, kw = make_axes(ax, **kw)
cb = Colorbar(cax, mappable, **kw)
def on_changed(m):
cb.set_cmap(m.get_cmap())
cb.set_clim(m.get_clim())
cb.update_bruteforce(m)
cbid = mappable.callbacksSM.connect('changed', on_changed)
mappable.colorbar = cb
ax.figure.sca(ax)
return cb
示例9: __init__
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
"""Initialize plot and plot the initial design"""
super(StressGUI, self).__init__(nelx, nely, title)
self.stress_im = self.ax.imshow(
np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
self.fig.colorbar(self.stress_im)
self.stress_calculator = stress_calculator
self.nu = nu
self.myColorMap = colormaps.ScalarMappable(
norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet)
示例10: plot_graph
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
g = nx.from_numpy_matrix(am)
if position is None:
position=nx.drawing.circular_layout(g)
fig = plt.figure()
if cls is None:
cls='r'
else:
# Make a user-defined colormap.
cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])
# Make a normalizer that will map the time values from
# [start_time,end_time+1] -> [0,1].
cnorm = mcol.Normalize(vmin=0, vmax=1)
# Turn these into an object that can be used to map time values to colors and
# can be passed to plt.colorbar().
cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
cpick.set_array([])
cls = cpick.to_rgba(cls)
plt.colorbar(cpick, ax=fig.add_subplot(111))
nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))
fig.savefig(os.path.join(self.plotdir, fig_name))
示例11: _plot
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def _plot(self, a, key, title, gx, gy, num_x, num_y):
pp.rcParams['figure.figsize'] = (
self._image_width / 300, self._image_height / 300
)
pp.title(title)
# Interpolate the data
rbf = Rbf(
a['x'], a['y'], a[key], function='linear'
)
z = rbf(gx, gy)
z = z.reshape((num_y, num_x))
# Render the interpolated data to the plot
pp.axis('off')
# begin color mapping
norm = matplotlib.colors.Normalize(
vmin=min(a[key]), vmax=max(a[key]), clip=True
)
mapper = cm.ScalarMappable(norm=norm, cmap='RdYlBu_r')
# end color mapping
image = pp.imshow(
z,
extent=(0, self._image_width, self._image_height, 0),
cmap='RdYlBu_r', alpha=0.5, zorder=100
)
pp.colorbar(image)
pp.imshow(self._layout, interpolation='bicubic', zorder=1, alpha=1)
# begin plotting points
for idx in range(0, len(a['x'])):
pp.plot(
a['x'][idx], a['y'][idx],
marker='o', markeredgecolor='black', markeredgewidth=1,
markerfacecolor=mapper.to_rgba(a[key][idx]), markersize=6
)
# end plotting points
fname = '%s_%s.png' % (key, self._title)
logger.info('Writing plot to: %s', fname)
pp.savefig(fname, dpi=300)
pp.close('all')
示例12: colorbar_index
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def colorbar_index(fig, cax, ncolors, cmap, drape_min_threshold, drape_max):
"""State-machine like function that creates a discrete colormap and plots
it on a figure that is passed as an argument.
Arguments:
fig (matplotlib.Figure): Instance of a matplotlib figure object.
cax (matplotlib.Axes): Axes instance to create the colourbar from.
This must be the Axes containing the data that your colourbar will be
mapped from.
ncolors (int): The number of colours in the discrete colourbar map.
cmap (str or Colormap object): Either the name of a matplotlib colormap, or
an object instance of the colormap, e.g. cm.jet
drape_min_threshold (float): Number setting the threshold level of the drape raster
This should match any threshold you have set to mask the drape/overlay raster.
drape_max (float): Similar to above, but for the upper threshold of your drape mask.
"""
discrete_cmap = discrete_colourmap(ncolors, cmap)
mappable = _cm.ScalarMappable(cmap=discrete_cmap)
mappable.set_array([])
#mappable.set_clim(-0.5, ncolors + 0.5)
mappable.set_clim(drape_min_threshold, drape_max)
print(type(fig))
print(type(mappable))
print(type(cax))
print()
cbar = _plt.colorbar(mappable, cax=cax) #switched from fig to plt to expose the labeling params
print(type(cbar))
#cbar.set_ticks(_np.linspace(0, ncolors, ncolors))
pad = ((ncolors - 1) / ncolors) / 2 # Move labels to center of bars.
cbar.set_ticks(_np.linspace(drape_min_threshold + pad, drape_max - pad,
ncolors))
return cbar
# Generate random colormap
示例13: make_amplitude_cmap
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def make_amplitude_cmap(
mapname="gray", vmin=1, vmax=1e5, ncolors=64, outname="amplitude-cog.cpt"
):
"""Write default colormap (amplitude-cog.cpt) for isce amplitude images.
Uses a LogNorm colormap by default since amplitude return values typically
span several orders of magnitude.
Parameters
----------
mapname : str
matplotlib colormap name
vmin : float
data value mapped to lower end of colormap
vmax : float
data value mapped to upper end of colormap
ncolors : int
number of discrete mapped values between vmin and vmax
"""
cmap = plt.get_cmap(mapname)
# NOTE for strong contrast amp return:
# cNorm = colors.Normalize(vmin=1e3, vmax=1e4)
cNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
write_cmap(outname, vals, scalarMap)
return outname
示例14: get_cmap
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def get_cmap(N):
'''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.'''
color_norm = colors.Normalize(vmin=0, vmax=N-1)
scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color
示例15: get_cmap
# 需要导入模块: from matplotlib import cm [as 别名]
# 或者: from matplotlib.cm import ScalarMappable [as 别名]
def get_cmap(N):
'''Returns a function that maps each index in 0, 1, ... N-1 to a distinct
RGB color.'''
color_norm = colors.Normalize(vmin=0, vmax=N)
scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color