本文整理匯總了Python中matplotlib.pyplot.Normalize方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.Normalize方法的具體用法?Python pyplot.Normalize怎麽用?Python pyplot.Normalize使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.Normalize方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_Normalize
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def test_Normalize():
norm = mcolors.Normalize()
vals = np.arange(-10, 10, 1, dtype=float)
_inverse_tester(norm, vals)
_scalar_tester(norm, vals)
_mask_tester(norm, vals)
# Handle integer input correctly (don't overflow when computing max-min,
# i.e. 127-(-128) here).
vals = np.array([-128, 127], dtype=np.int8)
norm = mcolors.Normalize(vals.min(), vals.max())
assert_array_equal(np.asarray(norm(vals)), [0, 1])
# Don't lose precision on longdoubles (float128 on Linux):
# for array inputs...
vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
norm = mcolors.Normalize(vals.min(), vals.max())
assert_array_equal(np.asarray(norm(vals)), [0, 1])
# and for scalar ones.
eps = np.finfo(np.longdouble).resolution
norm = plt.Normalize(1, 1 + 100 * eps)
# This returns exactly 0.5 when longdouble is extended precision (80-bit),
# but only a value close to it when it is quadruple precision (128-bit).
assert 0 < norm(1 + 50 * eps) < 1
示例2: show
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def show(x, gray_scale=False, jet_cmap=False, filename=None):
""" Show 'x' as an image on the screen.
"""
if jet_cmap is False:
img = data_to_image(x, gray_scale=gray_scale)
else:
if plt is None:
printcn(WARNING, 'pyplot not defined!')
return
cmap = plt.cm.jet
norm = plt.Normalize(vmin=x.min(), vmax=x.max())
img = cmap(norm(x))
if filename:
plt.imsave(filename, img)
else:
plt.imshow(img)
plt.show()
示例3: draw_heatmaps
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def draw_heatmaps(screen, surf, hm, thr=0.5, vmin=-15, vmax=10):
hm_idx = [
( 8, 0*hmsurf_size[0], 0*hmsurf_size[1]), # R. wrist
( 9, 1*hmsurf_size[0], 0*hmsurf_size[1]), # L. wrist
( 6, 0*hmsurf_size[0], 1*hmsurf_size[1]), # R. elbow
( 7, 1*hmsurf_size[0], 1*hmsurf_size[1]), # L. elbow
( 3, 0*hmsurf_size[0], 2*hmsurf_size[1]), # Head
( 0, 1*hmsurf_size[0], 2*hmsurf_size[1]), # Pelvis
(12, 0*hmsurf_size[0], 3*hmsurf_size[1]), # R. knee
(13, 1*hmsurf_size[0], 3*hmsurf_size[1])] # L. knee
for idx in hm_idx:
h = np.transpose(hm[:,:,idx[0]].copy(), (1, 0))
h[h < vmin] = vmin
h[h > vmax] = vmax
cmap = plt.cm.jet
norm = plt.Normalize(vmin=vmin, vmax=vmax)
cm = np.zeros((34, 34, 3))
cm[1:33, 1:33, :] = cmap(norm(h))[:,:,0:3]
cm = scipy.ndimage.zoom(cm, (5, 5, 1), order=1)
pygame.surfarray.pixels3d(surf)[:,:,:] = np.array(255.*cm, dtype=int)
screen.blit(surf, (idx[1] + img_size[0], idx[2]))
示例4: get_norm
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def get_norm(self, pad=None, i=None):
"""
Compute the adopted normalization at a given value of `i`, given the
value of <autofig.axes.AxDimension.pad> (or `pad`).
See also:
* <autofig.axes.AxDimension.norm>
Arguments
-----------
* `pad` (float, optional, default=None): override the padding. If not
provided or None, will use <autofig.axes.AxDimension.pad>.
* `i` (float, optional, default=None): the value to use for `i` when
computing visible data and limits.
Returns
--------
* (plt.Normalize object)
"""
return plt.Normalize(*self.get_lim(pad=pad, i=i))
示例5: get_sizes
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def get_sizes(self, i=None):
s = self.s.get_value(i=i, unit=self.axes_s.unit if self.axes_s is not None else None)
if self.do_sizescale:
if self.axes_s is not None:
sizes = self.axes_s.normalize(s, i=i)
else:
# fallback on 0.01-0.05 mapping for just this call
sall = self.s.get_value(unit=self.axes_s.unit if self.axes_s is not None else None)
norm = plt.Normalize(np.nanmin(sall), np.nanmax(sall))
sizes = norm(s) * 0.04+0.01
else:
if s is not None:
sizes = s
elif self.s.mode == 'pt':
sizes = 1
else:
sizes = 0.02
return sizes
示例6: _plot_3D_colored
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def _plot_3D_colored(x, y, z, color=None, rotate=False):
if color is None:
color = z
# Create a set of line segments
points = np.array([x, y, z]).T.reshape(-1, 1, 3)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Color
norm = plt.Normalize(color.min(), color.max())
cmap = plt.get_cmap("plasma")
colors = cmap(norm(color))
# Plot
fig = plt.figure()
ax = fig.gca(projection="3d")
for i in range(len(x) - 1):
seg = segments[i]
(l,) = ax.plot(seg[:, 0], seg[:, 1], seg[:, 2], color=colors[i])
l.set_solid_capstyle("round")
if rotate is True:
fig = _plot_3D_colored_rotate(fig, ax)
return fig
示例7: imshow2d
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def imshow2d(data, ax=None, cmap2d='brightwheel', huenorm=None, huevmin=None,
huevmax=None, lightnorm=None, lightvmin=None, lightvmax=None,
**kwargs):
"""
Plot 2 parameter 2D data array to current axis.
:param data: numpy array with shape (2, nwidth, nheight). The first index
corresponds to the hue and the second to the lightness of the
colors.
:param ax: a matplotlib axis instance.
:param cmap: either:
numpy array with shape (nwidth, nheight, 4) that contains
the 4 rgba values in hue (width) and lightness (height).
Can be obtained by a call to get_cmap2d(name).
or:
name where name is one of the following strings:
'brightwheel', 'darkwheel', 'hardwheel', 'newwheel',
'smoothwheel', 'wheel'
:param huenorm: a plt.Normalize() instance that normalizes the hue values.
:param huevmin: the minimum of the huevalues. Only used if huenorm=None.
:param huevmax: the maximum of the huevalues. Only used if huenorm=None.
:param lightnorm: a plt.Normalize() instance that normalizes the lightness
values.
:param lightvmin: the minimum of the lightness values.
Only used if lightnorm=None.
:param lightvmax: the maximum of the lightness values.
Only used if lightnorm=None.
:param **kwargs: remaining kwargs are passed to plt.imshow()
"""
if ax is None:
ax = plt.gca()
rgb_data = data2d_to_rgb(data, cmap2d=cmap2d,
huenorm=huenorm, huevmin=huevmin,
huevmax=huevmax, lightnorm=lightnorm,
lightvmin=lightvmin, lightvmax=lightvmax)
im = ax.imshow(rgb_data, **kwargs)
return im
示例8: _get_custom_colormap
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def _get_custom_colormap(colortext):
try:
colors = _get_color(colortext)
values = get_tick_val_col(colortext)
if colors is None or values is None:
return
norm = plt.Normalize(min(values), max(values))
tuples = list(zip(map(norm, values), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list(colortext, tuples)
except FileNotFoundError:
LOG.warning('No such file or directory: "%s"' % colortext)
return
return cmap
示例9: test_LogNorm
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def test_LogNorm():
"""
LogNorm ignored clip, now it has the same
behavior as Normalize, e.g., values > vmax are bigger than 1
without clip, with clip they are 1.
"""
ln = mcolors.LogNorm(clip=True, vmax=5)
assert_array_equal(ln([1, 6]), [0, 1.0])
示例10: test_PowerNorm
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def test_PowerNorm():
a = np.array([0, 0.5, 1, 1.5], dtype=float)
pnorm = mcolors.PowerNorm(1)
norm = mcolors.Normalize()
assert_array_almost_equal(norm(a), pnorm(a))
a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
expected = [0, 0, 1/16, 1/4, 1]
pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
assert_array_almost_equal(pnorm(a), expected)
assert pnorm(a[0]) == expected[0]
assert pnorm(a[2]) == expected[2]
assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])
# Clip = True
a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
expected = [0, 0, 0, 1, 1]
pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
assert_array_almost_equal(pnorm(a), expected)
assert pnorm(a[0]) == expected[0]
assert pnorm(a[-1]) == expected[-1]
# Clip = True at call time
a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
expected = [0, 0, 0, 1, 1]
pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
assert_array_almost_equal(pnorm(a, clip=True), expected)
assert pnorm(a[0], clip=True) == expected[0]
assert pnorm(a[-1], clip=True) == expected[-1]
示例11: test_ndarray_subclass_norm
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def test_ndarray_subclass_norm(recwarn):
# Emulate an ndarray subclass that handles units
# which objects when adding or subtracting with other
# arrays. See #6622 and #8696
class MyArray(np.ndarray):
def __isub__(self, other):
raise RuntimeError
def __add__(self, other):
raise RuntimeError
data = np.arange(-10, 10, 1, dtype=float)
data.shape = (10, 2)
mydata = data.view(MyArray)
for norm in [mcolors.Normalize(), mcolors.LogNorm(),
mcolors.SymLogNorm(3, vmax=5, linscale=1),
mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
mcolors.PowerNorm(1)]:
assert_array_equal(norm(mydata), norm(data))
fig, ax = plt.subplots()
ax.imshow(mydata, norm=norm)
fig.canvas.draw()
assert len(recwarn) == 0
recwarn.clear()
示例12: colorline
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def colorline(x, y, cmap=None, cm_range=(0, 0.7), **kwargs):
"""Colorline plots a trajectory of (x,y) points with a colormap"""
# plt.plot(x, y, '-k', zorder=1)
# plt.scatter(x, y, s=40, c=plt.cm.RdBu(np.linspace(0,1,40)), zorder=2, edgecolor='k')
assert len(cm_range)==2, "cm_range must have (min, max)"
assert len(x) == len(y), "x and y must have the same number of elements!"
ax = kwargs.get('ax', plt.gca())
lw = kwargs.get('lw', 2)
if cmap is None:
cmap=plt.cm.Blues_r
t = np.linspace(cm_range[0], cm_range[1], len(x))
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 1),
zorder=50)
lc.set_array(t)
lc.set_linewidth(lw)
ax.add_collection(lc)
return lc
示例13: create_cmap
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def create_cmap(values, colors):
from matplotlib.pyplot import Normalize
import matplotlib
norm = Normalize(min(values), max(values))
tuples = list(zip(map(norm, values), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
return cmap, norm
示例14: compute_node_colors
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def compute_node_colors(self):
"""Compute the node colors. Also computes the colorbar."""
data = [self.graph.nodes[n][self.node_color] for n in self.nodes]
if self.group_order == "alphabetically":
data_reduced = sorted(list(set(data)))
elif self.group_order == "default":
data_reduced = list(unique_everseen(data))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["continuous"].mpl_colormap)
elif dtype == "continuous" and is_data_diverging(data):
cmap = get_cmap(cmaps["diverging"].mpl_colormap)
for d in data:
idx = data_reduced.index(d) / n_grps
self.node_colors.append(cmap(idx))
# Add colorbar if required.ListedColormap
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = []
示例15: compute_edge_colors
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import Normalize [as 別名]
def compute_edge_colors(self):
"""Compute the edge colors."""
data = [self.graph.edges[n][self.edge_color] for n in self.edges]
data_reduced = sorted(list(set(data)))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["weights"])
for d in data:
idx = data_reduced.index(d) / n_grps
self.edge_colors.append(cmap(idx))
# Add colorbar if required.
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = []