本文整理汇总了Python中matplotlib.collections.PatchCollection.set_cmap方法的典型用法代码示例。如果您正苦于以下问题:Python PatchCollection.set_cmap方法的具体用法?Python PatchCollection.set_cmap怎么用?Python PatchCollection.set_cmap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.PatchCollection
的用法示例。
在下文中一共展示了PatchCollection.set_cmap方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
class ArrayDisplay:
"""
Display a top-town view of a telescope array
"""
def __init__(self, telx, tely, mirrorarea,
axes=None, title="Array", autoupdate=True):
patches = [Circle(xy=(x, y), radius=np.sqrt(a))
for x, y, a in zip(telx, tely, mirrorarea)]
self.autoupdate = autoupdate
self.telescopes = PatchCollection(patches)
self.telescopes.set_clim(0, 100)
self.telescopes.set_array(np.zeros(len(telx)))
self.telescopes.set_cmap('spectral_r')
self.telescopes.set_edgecolor('none')
self.axes = axes if axes is not None else plt.gca()
self.axes.add_collection(self.telescopes)
self.axes.set_aspect(1.0)
self.axes.set_title(title)
self.axes.set_xlim(-1000, 1000)
self.axes.set_ylim(-1000, 1000)
self.bar = plt.colorbar(self.telescopes)
self.bar.set_label("Value")
@property
def values(self):
"""An array containing a value per telescope"""
return self.telescopes.get_array()
@values.setter
def values(self, values):
""" set the telescope colors to display """
self.telescopes.set_array(values)
self._update()
def _update(self):
""" signal a redraw if necessary """
if self.autoupdate:
plt.draw()
示例2: draw1DColumn
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def draw1DColumn(ax, x, val, thk, width=30, ztopo=0, cmin=1, cmax=1000,
cmap=None, name=None, textoffset=0.0):
"""Draw a 1D column (e.g., from a 1D inversion) on a given ax.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from pygimli.mplviewer import draw1DColumn
>>> thk = [1, 2, 3, 4]
>>> val = thk
>>> fig, ax = plt.subplots()
>>> draw1DColumn(ax, 0.5, val, thk, width=0.1, cmin=1, cmax=4, name="VES")
<matplotlib.collections.PatchCollection object at ...>
>>> ax.set_ylim(-np.sum(thk), 0)
(-10, 0)
"""
z = -np.hstack((0., np.cumsum(thk), np.sum(thk) * 1.5)) + ztopo
recs = []
for i in range(len(val)):
recs.append(Rectangle((x - width / 2., z[i]), width, z[i + 1] - z[i]))
pp = PatchCollection(recs)
col = ax.add_collection(pp)
pp.set_edgecolor(None)
pp.set_linewidths(0.0)
if cmap is not None:
if isinstance(cmap, str):
pp.set_cmap(pg.mplviewer.cmapFromName(cmap))
else:
pp.set_cmap(cmap)
pp.set_norm(colors.LogNorm(cmin, cmax))
pp.set_array(np.array(val))
pp.set_clim(cmin, cmax)
if name:
ax.text(x+textoffset, ztopo, name, ha='center', va='bottom')
updateAxes_(ax)
return col
示例3: showStitchedModels
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def showStitchedModels(mods, axes=None, cmin=None, cmax=None, **kwargs):
"""
Show several 1d block models as (stitched) section.
"""
x = kwargs.pop('x', np.arange(len(mods)))
topo = kwargs.pop('topo', x*0)
nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1
if cmin is None or cmax is None:
cmin = 1e9
cmax = 1e-9
for model in mods:
res = np.asarray(model)[nlay - 1:nlay * 2 - 1]
cmin = min(cmin, min(res))
cmax = max(cmax, max(res))
if kwargs.pop('sameSize', True): # all having the same width
dx = np.ones_like(x)*np.median(np.diff(x))
else:
dx = np.diff(x) * 1.05
dx = np.hstack((dx, dx[-1]))
x1 = x - dx / 2
if axes is None:
fig, ax = plt.subplots()
else:
ax = axes
fig = ax.figure
# ax.plot(x, x * 0., 'k.')
zm = kwargs.pop('zm', None)
maxz = 0.
if zm is not None:
maxz = zm
recs = []
RES = []
for i, mod in enumerate(mods):
mod1 = np.asarray(mod)
res = mod1[nlay - 1:]
RES.extend(res)
thk = mod1[:nlay - 1]
thk = np.hstack((thk, thk[-1]))
z = np.hstack((0., np.cumsum(thk)))
if zm is not None:
thk[-1] = zm - z[-2]
z[-1] = zm
else:
maxz = max(maxz, z[-1])
for j in range(len(thk)):
recs.append(Rectangle((x1[i], topo[i]-z[j]), dx[i], -thk[j]))
pp = PatchCollection(recs, edgecolors=kwargs.pop('edgecolors', 'none'))
pp.set_edgecolor(kwargs.pop('edgecolors', 'none'))
pp.set_linewidths(0.0)
ax.add_collection(pp)
if 'cmap' in kwargs:
pp.set_cmap(kwargs['cmap'])
print(cmin, cmax)
norm = LogNorm(cmin, cmax)
pp.set_norm(norm)
pp.set_array(np.array(RES))
# pp.set_clim(cmin, cmax)
ax.set_ylim((-maxz, max(topo)))
ax.set_xlim((x1[0], x1[-1] + dx[-1]))
cbar = None
if kwargs.pop('colorBar', True):
cbar = plt.colorbar(pp, ax=ax, norm=norm, orientation='horizontal',
aspect=60) # , ticks=[1, 3, 10, 30, 100, 300])
if 'ticks' in kwargs:
cbar.set_ticks(kwargs['ticks'])
# cbar.autoscale_None()
if axes is None: # newly created fig+ax
return fig, ax
else: # already given, better give back color bar
return cbar
示例4: patchValMap
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None,
logScale=None, label=None, dx=1, dy=None, **kwargs):
""" plot previously generated (generateVecMatrix) y map (category)
Parameters
----------
A : iterable
to show
xvec : dict {i:num}
dict (must match A.shape[0])
ymap : iterable
vector for x axis (must match A.shape[0])
ax : mpl.axis
axis to plot, if not given a new figure is created
cMin/cMax : float
minimum/maximum color values
logScale : bool
logarithmic colour scale [min(A)>0]
label : string
colorbar label
"""
if cMin is None:
cMin = np.min(vals)
if cMax is None:
cMax = np.max(vals)
if logScale is None:
logScale = (cMin > 0.0)
if logScale:
norm = LogNorm(vmin=cMin, vmax=cMax)
else:
norm = Normalize(vmin=cMin, vmax=cMax)
if 'ax' is None:
fig, ax = plt.subplots()
recs = []
if dy is None: # map y values to unique
ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}
for i in range(len(vals)):
recs.append(Rectangle((xvec[i]-dx/2, ymap[yvec[i]]-0.5), dx, 1))
else:
for i in range(len(vals)):
recs.append(Rectangle((xvec[i]-dx/2, yvec[i]-dy/2), dx, dy))
pp = PatchCollection(recs)
col = ax.add_collection(pp)
pp.set_edgecolor(None)
pp.set_linewidths(0.0)
if 'cmap' in kwargs:
pp.set_cmap(kwargs.pop('cmap'))
pp.set_norm(norm)
pp.set_array(np.array(vals))
pp.set_clim(cMin, cMax)
ax.set_xlim(min(xvec)-dx/2, max(xvec)+dx/2)
ax.set_ylim(len(ymap)-0.5, -0.5)
updateAxes_(ax)
cbar = None
if kwargs.pop('colorBar', True):
cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5,
label=label)
return ax, cbar, ymap
示例5: patchMatrix
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def patchMatrix(A, xmap=None, ymap=None, ax=None, cMin=None, cMax=None,
logScale=None, label=None, dx=1, **kwargs):
""" plot previously generated (generateVecMatrix) matrix
Parameters
----------
A : numpy.array2d
matrix to show
xmap : dict {i:num}
dict (must match A.shape[0])
ymap : iterable
vector for x axis (must match A.shape[0])
ax : mpl.axis
axis to plot, if not given a new figure is created
cMin/cMax : float
minimum/maximum color values
logScale : bool
logarithmic colour scale [min(A)>0]
label : string
colorbar label
"""
mat = np.ma.masked_where(A == 0.0, A, False)
if cMin is None:
cMin = np.min(mat)
if cMax is None:
cMax = np.max(mat)
if logScale is None:
logScale = (cMin > 0.0)
if logScale:
norm = LogNorm(vmin=cMin, vmax=cMax)
else:
norm = Normalize(vmin=cMin, vmax=cMax)
if 'ax' is None:
fig, ax = plt.subplots()
iy, ix = np.nonzero(A) # != 0)
recs = []
vals = []
for i in range(len(ix)):
recs.append(Rectangle((ix[i]-dx/2, iy[i]-0.5), dx, 1))
vals.append(A[iy[i], ix[i]])
pp = PatchCollection(recs)
col = ax.add_collection(pp)
pp.set_edgecolor(None)
pp.set_linewidths(0.0)
if 'cmap' in kwargs:
pp.set_cmap(kwargs.pop('cmap'))
pp.set_norm(norm)
pp.set_array(np.array(vals))
pp.set_clim(cMin, cMax)
xval = [k for k in xmap.keys()]
ax.set_xlim(min(xval)-dx/2, max(xval)+dx/2)
ax.set_ylim(len(ymap)+0.5, -0.5)
updateAxes_(ax)
cbar = None
if kwargs.pop('colorBar', True):
cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5,
label=label)
return ax, cbar
示例6: factcamera
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
#.........这里部分代码省略.........
Attributes
----------
data : array like with shape 1440
the data you want to plot into the pixels
pixelset : boolean array with shape 1440
the pixels where pixelset is True are marked with 'pixelsetcolour'
[default: None]
pixelsetcolour : a matplotlib conform colour representation
the colour for the pixels in 'pixelset',
[default: green]
pixelcoords : the coordinates for the pixels in form [x-values, y-values]
if None, the package resource is used
[default: None]
cmap : str or matplotlib colormap instance
the colormap to use for plotting the 'dataset'
[default: gray]
vmin : float
the minimum for the colorbar, if None min(dataset[event]) is used
[default: None]
vmax : float
the maximum for the colorbar, if None max(dataset[event]) is used
[default: None]
picker: bool
if True then the the pixel are made clickable to show information
"""
self.set_aspect('equal')
if picker is True:
fig = self.get_figure()
fig.canvas.mpl_connect("pick_event", onpick)
# if the axes limit is still (0,1) assume new axes
if self.get_xlim() == (0, 1) and self.get_ylim() == (0, 1):
self.set_xlim(-200, 200)
self.set_ylim(-200, 200)
if pixelcoords is None:
pixel_x, pixel_y = get_pixel_coords()
else:
pixel_x, pixel_y = pixelcoords
if vmin is None:
vmin = np.min(data)
if vmax is None:
vmax = np.max(data)
edgecolors = np.array(1440*["k"])
if pixelset is None:
pixelset = np.zeros(1440, dtype=np.bool)
_pixelset = np.array(pixelset)
if _pixelset.ndim == 1:
if _pixelset.shape != (1440,):
pixelset = np.zeros(1440, dtype=np.bool)
pixelset[_pixelset] = True
else:
pixelset = np.array(_pixelset, dtype=np.bool)
edgecolors[pixelset] = pixelsetcolour
elif _pixelset.ndim == 2:
for pixelset, colour in zip(_pixelset, pixelsetcolour):
edgecolors[pixelset] = colour
intersect = np.logical_and(_pixelset[0], _pixelset[1])
edgecolors[intersect] = intersectcolour
else:
raise ValueError(
"""pixelset needs to be one of:
1. list of pixelids
2. 1d bool array with shape (1440,)
3. 2d bool array with shape (2, 1440)
"""
)
patches = []
for x, y, ec in zip(pixel_x, pixel_y, edgecolors):
patches.append(
RegularPolygon(
xy=(x, y),
numVertices=6,
radius=0.95*9.5/np.sqrt(3),
orientation=0., # in radians
)
)
if linewidth is None:
linewidth = calc_linewidth(self)
collection = PatchCollection(patches, picker=0)
collection.set_linewidth(linewidth)
collection.set_edgecolors(edgecolors)
collection.set_cmap(cmap)
collection.set_array(data)
collection.set_clim(vmin, vmax)
self.add_collection(collection)
return collection
示例7: plot_polygon_collection
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def plot_polygon_collection(ax, geoms, values=None, color=None,
cmap=None, vmin=None, vmax=None, **kwargs):
"""
Plots a collection of Polygon and MultiPolygon geometries to `ax`
Parameters
----------
ax : matplotlib.axes.Axes
where shapes will be plotted
geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)
values : a sequence of `N` values, optional
Values will be mapped to colors using vmin/vmax/cmap. They should
have 1:1 correspondence with the geometries (not their components).
Otherwise follows `color` / `facecolor` kwargs.
edgecolor : single color or sequence of `N` colors
Color for the edge of the polygons
facecolor : single color or sequence of `N` colors
Color to fill the polygons. Cannot be used together with `values`.
color : single color or sequence of `N` colors
Sets both `edgecolor` and `facecolor`
**kwargs
Additional keyword arguments passed to the collection
Returns
-------
collection : matplotlib.collections.Collection that was plotted
"""
from descartes.patch import PolygonPatch
from matplotlib.collections import PatchCollection
geoms, values = _flatten_multi_geoms(geoms, values)
if None in values:
values = None
# PatchCollection does not accept some kwargs.
if 'markersize' in kwargs:
del kwargs['markersize']
# color=None overwrites specified facecolor/edgecolor with default color
if color is not None:
kwargs['color'] = color
collection = PatchCollection([PolygonPatch(poly) for poly in geoms],
**kwargs)
if values is not None:
collection.set_array(np.asarray(values))
collection.set_cmap(cmap)
collection.set_clim(vmin, vmax)
ax.add_collection(collection, autolim=True)
ax.autoscale_view()
return collection
示例8: str
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
#.........这里部分代码省略.........
return self.pixels.norm
@norm.setter
def norm(self, norm):
if norm == 'lin':
self.pixels.norm = Normalize()
elif norm == 'log':
self.pixels.norm = LogNorm()
self.pixels.autoscale() # this is to handle matplotlib bug #5424
elif norm == 'symlog':
self.pixels.norm = SymLogNorm(linthresh=1.0)
self.pixels.autoscale()
elif isinstance(norm, Normalize):
self.pixels.norm = norm
else:
raise ValueError("Unsupported norm: '{}', options are 'lin',"
"'log','symlog', or a matplotlib Normalize object"
.format(norm))
self.update(force=True)
self.pixels.autoscale()
@property
def cmap(self):
"""
Color map to use. Either a name or `matplotlib.colors.ColorMap`
instance, e.g. from `matplotlib.pyplot.cm`
"""
return self.pixels.get_cmap()
@cmap.setter
def cmap(self, cmap):
self.pixels.set_cmap(cmap)
self._update()
@property
def image(self):
"""The image displayed on the camera (1D array of pixel values)"""
return self.pixels.get_array()
@image.setter
def image(self, image):
"""
Change the image displayed on the Camera.
Parameters
----------
image: array_like
array of values corresponding to the pixels in the CameraGeometry.
"""
image = np.asanyarray(image)
if image.shape != self.geom.pix_x.shape:
raise ValueError(
"Image has a different shape {} than the "
"given CameraGeometry {}"
.format(image.shape, self.geom.pix_x.shape)
)
self.pixels.set_array(image[self.geom.mask])
self.pixels.changed()
if self.autoscale:
self.pixels.autoscale()
self._update()
def _update(self, force=False):
示例9: patchValMap
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
#.........这里部分代码省略.........
else:
norm = Normalize(vmin=cMin, vmax=cMax)
if ax is None:
ax = plt.subplots()[1]
recs = []
circular = kwargs.pop('circular', False)
if circular:
recs = [None] * len(xvec)
if dy is None: # map y values to unique
ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}
xyMap = {}
for i, y in enumerate(yvec):
if y not in xyMap:
xyMap[y] = []
xyMap[y].append(i)
# maxR = max(ymap.values()) # what's that for? not used
dR = 1 / (len(ymap.values())+1)
# dOff = np.pi / 2 # what's that for? not used
for y, xIds in xyMap.items():
r = 1. - dR*(ymap[y]+1)
# ax.plot(r * np.cos(xvec[xIds]),
# r * np.sin(xvec[xIds]), 'o')
# print(y, ymap[y])
for i in xIds:
phi = xvec[i]
# x = r * np.cos(phi) # what's that for? not used
y = r * np.sin(phi)
dPhi = (xvec[1] - xvec[0])
recs[i] = Wedge((0., 0.), r + dR/1.5,
(phi - dPhi)*360/(2*np.pi),
(phi + dPhi)*360/(2*np.pi),
width=dR,
zorder=1+r)
# if i < 5:
# ax.text(x, y, str(i))
# pg.wait()
else:
raise("Implementme")
else:
if dy is None: # map y values to unique
ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}
for i in range(len(vals)):
recs.append(Rectangle((xvec[i] - dx / 2, ymap[yvec[i]] - 0.5),
dx, 1))
else:
for i in range(len(vals)):
recs.append(Rectangle((xvec[i] - dx / 2, yvec[i] - dy / 2),
dx, dy))
ax.set_xlim(min(xvec) - dx / 2, max(xvec) + dx / 2)
ax.set_ylim(len(ymap) - 0.5, -0.5)
pp = PatchCollection(recs)
# ax.clear()
col = ax.add_collection(pp)
pp.set_edgecolor(None)
pp.set_linewidths(0.0)
if circular:
pp.set_edgecolor('black')
pp.set_linewidths(0.1)
cmap = pg.mplviewer.cmapFromName(**kwargs)
if kwargs.pop('markOutside', False):
cmap.set_bad('grey')
cmap.set_under('darkgrey')
cmap.set_over('lightgrey')
cmap.set_bad('black')
pp.set_cmap(cmap)
pp.set_norm(norm)
pp.set_array(vals)
pp.set_clim(cMin, cMax)
updateAxes_(ax)
cbar = kwargs.pop('colorBar', True)
ori = kwargs.pop('orientation', 'horizontal')
if cbar in ['horizontal', 'vertical']:
ori = cbar
cbar = True
if cbar is True: # not for cbar=1, which is really confusing!
cbar = pg.mplviewer.createColorBar(col, cMin=cMin, cMax=cMax,
nLevs=5, label=label,
orientation=ori)
elif cbar is not False:
# .. cbar is an already existing cbar .. so we update its values
pg.mplviewer.updateColorBar(cbar, cMin=cMin, cMax=cMax,
nLevs=5, label=label)
updateAxes_(ax)
return ax, cbar, ymap
示例10: CameraPlot
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
class CameraPlot(object):
'''A Class for a camera pixel'''
def __init__(
self,
telescope,
ax,
data=None,
cmap='gray',
vmin=None,
vmax=None,
):
'''
:telescope: the telescope class for the pixel
:data: array-like with one value for each pixel
:cmap: a matpixellib colormap string or instance
:vmin: minimum value of the colormap
:vmax: maximum value of the colormap
'''
self.telescope = telescope
if data is None:
data = np.zeros(telescope.n_pixel)
patches = []
if telescope.pixel_shape == 'hexagon':
for xy in zip(telescope.pixel_x, telescope.pixel_y):
patches.append(
RegularPolygon(
xy=xy,
numVertices=6,
radius=telescope.pixel_size,
orientation=telescope.pixel_orientation,
)
)
self.pixel = PatchCollection(patches)
self.pixel.set_linewidth(0)
self.pixel.set_cmap(cmap)
self.pixel.set_array(data)
self.pixel.set_clim(vmin, vmax)
self.vmin = vmin
self.vmax = vmax
self.ax = ax
self.ax.add_collection(self.pixel)
self.ax.set_xlim(
self.telescope.pixel_x.min() - 2 * self.telescope.pixel_size,
self.telescope.pixel_x.max() + 2 * self.telescope.pixel_size,
)
self.ax.set_ylim(
self.telescope.pixel_y.min() - 2 * self.telescope.pixel_size,
self.telescope.pixel_y.max() + 2 * self.telescope.pixel_size,
)
@property
def data(self):
return self.pixel.get_array()
@data.setter
def data(self, data):
self.pixel.set_array(data)
if not self.vmin or not self.vmax:
self.pixel.autoscale()
self.pixel.changed()
示例11: bool
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
#.........这里部分代码省略.........
self.axes.autoscale_view()
# set up a patch to display when a pixel is clicked (and
# pixel_picker is enabled):
self._active_pixel = copy.copy(patches[0])
self._active_pixel.set_facecolor('r')
self._active_pixel.set_alpha(0.5)
self._active_pixel.set_linewidth(2.0)
self._active_pixel.set_visible(False)
self.axes.add_patch(self._active_pixel)
self._active_pixel_label = plt.text(self._active_pixel.xy[0],
self._active_pixel.xy[1],
"0",
horizontalalignment='center',
verticalalignment='center')
self._active_pixel_label.set_visible(False)
# enable ability to click on pixel and do something (can be
# enabled on-the-fly later as well:
if allow_pick:
self.enable_pixel_picker()
def enable_pixel_picker(self):
""" enable ability to click on pixels """
self.pixels.set_picker(True) # enable click
self.pixels.set_pickradius(sqrt(u.Quantity(self.geom.pix_area[0])
.value) / np.pi)
self.pixels.set_snap(True) # snap cursor to pixel center
self.axes.figure.canvas.mpl_connect('pick_event', self._on_pick)
def set_cmap(self, cmap):
""" Change the color map
Parameters
----------
self: type
description
cmap: `matplotlib.colors.ColorMap`
a color map, e.g. from `matplotlib.pyplot.cm.*`
"""
self.pixels.set_cmap(cmap)
def set_image(self, image):
"""
Change the image displayed on the Camera.
Parameters
----------
image: array_like
array of values corresponding to the pixels in the CameraGeometry.
"""
image = np.asanyarray(image)
if image.shape != self.geom.pix_x.shape:
raise ValueError("Image has a different shape {} than the"
"given CameraGeometry {}"
.format(image.shape, self.geom.pix_x.shape))
self.pixels.set_array(image)
self.update()
def update(self):
""" signal a redraw if necessary """
if self.autoupdate:
plt.draw()
示例12: Plot2D
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def Plot2D(self, xy=None, elecon=None, u=None, color=None, ax=None, show=0,
weight=None, colorby=None, linestyle='-', label=None, xlim=None,
ylim=None, filename=None, **kwds):
assert self.dimensions == 2
from matplotlib.patches import Polygon
import matplotlib.lines as mlines
from matplotlib.collections import PatchCollection
from matplotlib.cm import coolwarm, Spectral
import matplotlib.pyplot as plt
if xy is None:
xy = array(self.coord)
if elecon is None:
elecon = []
for blk in self.eleblx:
elecon.extend(blk.elecon.tolist())
elecon = asarray(elecon)
if u is not None:
xy += u.reshape(xy.shape)
patches = []
for points in xy[elecon[:]]:
quad = Polygon(points, True)
patches.append(quad)
if ax is None:
fig, ax = plt.subplots()
#colors = 100 * random.rand(len(patches))
p = PatchCollection(patches, linewidth=weight, **kwds)
if colorby is not None:
colorby = asarray(colorby).flatten()
if len(colorby) == len(xy):
# average value in element
colorby = array([average(colorby[points]) for points in elecon])
p.set_cmap(Spectral) #coolwarm)
p.set_array(colorby)
p.set_clim(vmin=colorby.min(), vmax=colorby.max())
fig.colorbar(p)
else:
p.set_edgecolor(color)
p.set_facecolor('None')
p.set_linewidth(weight)
p.set_linestyle(linestyle)
if label:
ax.plot([], [], color=color, linestyle=linestyle, label=label)
ax.add_collection(p)
if not ylim:
ymin, ymax = amin(xy[:,1]), amax(xy[:,1])
dy = max(abs(ymin*.05), abs(ymax*.05))
ax.set_ylim([ymin-dy, ymax+dy])
else:
ax.set_ylim(ylim)
if not xlim:
xmin, xmax = amin(xy[:,0]), amax(xy[:,0])
dx = max(abs(xmin*.05), abs(xmax*.05))
ax.set_xlim([xmin-dx, xmax+dx])
else:
ax.set_xlim(xlim)
ax.set_aspect('equal')
if show:
plt.show()
if filename is not None:
plt.legend()
plt.savefig(filename, transparent=True,
bbox_inches="tight", pad_inches=0)
return ax
示例13: plot_polygon_collection
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_cmap [as 别名]
def plot_polygon_collection(ax, geoms, colors_or_values, plot_values,
vmin=None, vmax=None, cmap=None,
edgecolor='black', alpha=0.5, linewidth=1.0, **kwargs):
"""
Plots a collection of Polygon and MultiPolygon geometries to `ax`
Parameters
----------
ax : matplotlib.axes.Axes
where shapes will be plotted
geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)
colors_or_values : a sequence of `N` values or RGBA tuples
It should have 1:1 correspondence with the geometries (not their components).
plot_values : bool
If True, `colors_or_values` is interpreted as a list of values, and will
be mapped to colors using vmin/vmax/cmap (which become required).
Otherwise `colors_or_values` is interpreted as a list of colors.
Returns
-------
collection : matplotlib.collections.Collection that was plotted
"""
from descartes.patch import PolygonPatch
from matplotlib.collections import PatchCollection
components, component_colors_or_values = _flatten_multi_geoms(
geoms, colors_or_values)
# PatchCollection does not accept some kwargs.
if 'markersize' in kwargs:
del kwargs['markersize']
collection = PatchCollection([PolygonPatch(poly) for poly in components],
linewidth=linewidth, edgecolor=edgecolor,
alpha=alpha, **kwargs)
if plot_values:
collection.set_array(np.array(component_colors_or_values))
collection.set_cmap(cmap)
collection.set_clim(vmin, vmax)
else:
# set_color magically sets the correct combination of facecolor and
# edgecolor, based on collection type.
collection.set_color(component_colors_or_values)
# If the user set facecolor and/or edgecolor explicitly, the previous
# call to set_color might have overridden it (remember, the 'color' may
# have come from plot_series, not from the user). The user should be
# able to override matplotlib's default behavior, by setting them again
# after set_color.
if 'facecolor' in kwargs:
collection.set_facecolor(kwargs['facecolor'])
if edgecolor:
collection.set_edgecolor(edgecolor)
ax.add_collection(collection, autolim=True)
ax.autoscale_view()
return collection