本文整理汇总了Python中matplotlib.collections.PolyCollection.set_array方法的典型用法代码示例。如果您正苦于以下问题:Python PolyCollection.set_array方法的具体用法?Python PolyCollection.set_array怎么用?Python PolyCollection.set_array使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.PolyCollection
的用法示例。
在下文中一共展示了PolyCollection.set_array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotcelldata
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def plotcelldata(self, z, xlims=None, ylims=None, colorbar=True, **kwargs):
"""
Plot cell centered data
"""
ax=plt.gca()
fig = plt.gcf()
# Find the colorbar limits if unspecified
if self.clim is None:
self.clim = [z.min(),z.max()]
# Set the xy limits
if xlims is None or ylims is None:
xlims=self.xlims()
ylims=self.ylims()
collection = PolyCollection(self.xy(),closed=False,**kwargs)
collection.set_array(z)
collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
collection.set_edgecolors(collection.to_rgba(z))
ax.add_collection(collection)
ax.set_aspect('equal')
ax.set_xlim(xlims)
ax.set_ylim(ylims)
axcb=None
if colorbar:
axcb = fig.colorbar(collection)
return fig, ax, collection, axcb
示例2: set_data
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def set_data(self, zname=None, zdata=None, zcolor=None, plot_type="poly"):
if zdata!=None:
if plot_type is "poly":
if zname not in self.clts: #plottables['plotted']:#self.pd.list_data():
clt=PolyCollection([], alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False)
if zcolor is not None:
clt.set_color(colorConverter.to_rgba(zcolor))
self.clts[zname]=clt
self.axe.add_collection(self.clts[zname])
self.clts[zname].set_verts(zdata)
elif plot_type is "line":
if zname not in self.clts:
clt=LineCollection(zdata)#, linewidths=(0.5, 1, 1.5, 2),
#linestyles='solid', colors=("red", "blue", "green"))
if zcolor is not None:
clt.set_color(zcolor)
else:
clt.set_array(arange(len(zdata)))
else:
self.clts[zname].set_verts(zdata)
#self.set_xlim(x.min(), x.max())
#self.set_ylim(ys.min(), ys.max())
elif plot_type is "scatter":
self.axe.scatter(zdata, zdata)
elif plot_type is "colormap":
self.axe.pcolormesh(x, y, z)
if 0:
x = arange(3)
ys = array([x + i for i in arange(5)])
#xdata=arange(len(getattr(self, zname)))
data=[list(zip(x, y)) for y in ys]
line_segments = LineCollection(data,
linewidths=1,
linestyles='solid',
colors=mycolors)
print data
print len(data)
#print line_segments.properties()
#print line_segments.set_hatch("O")
#print dir(self.axe)
print [p.vertices for p in line_segments.get_paths()]#)
print line_segments.get_segments()
示例3: plot_trimesh2D
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def plot_trimesh2D(verts, faces, val=None, cmap=plt.cm.get_cmap(),
vmin=None, vmax=None, mirror=False, **kw):
"""Plot a mesh of triangles, from directly above, without all this
3D stuff.
Input verts N x 3 array of vertex locations
faces M x 3 array of vertex indices for each face
val M list of values for each vertex, used for coloring
cmap colormap, defaulting to current colormap
vmin lower limit for coloring, defaulting to min(val)
vmax upper limit for coloring, defaulting to max(val)
mirror flag for mirror around x=0
Other keyword pairs are passed to PolyCollection
"""
v = array([[verts[ind,:2] for ind in face] for face in faces])
if mirror:
v = r_[v, v * [-1,1]]
if val is not None:
val = array(val)
poly = PolyCollection(v, cmap=cmap, norm=Normalize(clip=True), **kw)
poly.set_array(val)
poly.set_clim(vmin, vmax)
poly.set_facecolors(poly.norm(val))
ax = plt.gca()
ax.add_collection(poly)
ax.axis('image')
if val is not None:
# This magic dohickey is used by colorbar() and clim(), for example
plt.gci._current = poly
plt.draw() # Seems like should be draw_if_interactive(), but that doesn't
# work, for some unexplained reason.
return poly
示例4: plotSolution
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def plotSolution(self, heatExch, axes, var, zmin = None, zmax = None, cmap = cm.jet):
vertexIDs = self.mesh._orderedCellVertexIDs
vertexCoords = self.mesh.vertexCoords
xCoords = np.take(vertexCoords[0], vertexIDs)
yCoords = np.take(vertexCoords[1], vertexIDs)
polys = []
for x, y in zip(xCoords.swapaxes(0,1), yCoords.swapaxes(0,1)):
if hasattr(x, 'mask'):
x = x.compressed()
if hasattr(y, 'mask'):
y = y.compressed()
polys.append(zip(x,y))
from matplotlib.collections import PolyCollection
# Set limits
xmin = xCoords.min()
xmax = xCoords.max()
ymin = yCoords.min()
ymax = yCoords.max()
axes.set_xlim(xmin=xmin, xmax=xmax)
axes.set_ylim(ymin=ymin, ymax=ymax)
Z = var.value
if (zmin is None):
zmin = np.min(Z)
if (zmax is None):
zmax = np.max(Z)
norm = Normalize(zmin, zmax)
collection = PolyCollection(polys, cmap = cmap, norm = norm)
collection.set_linewidth(0.)
axes.add_collection(collection)
cbax, _ = colorbar.make_axes(axes)
cb = colorbar.ColorbarBase(cbax, cmap=cmap,
norm = norm)
cb.set_label('Temperature [K]')
collection.set_array(np.array(Z))
示例5: overlayFan
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
#.........这里部分代码省略.........
if(isinstance(myData,pydarn.sdio.beamData)): myData = [myData]
gs_flg,lines = [],[]
if fill: verts,intensities = [],[]
else: verts,intensities = [[],[]],[[],[]]
#loop through gates with scatter
for myBeam in myData:
for k in range(0,len(myBeam.fit.slist)):
if myBeam.fit.slist[k] not in fov.gates: continue
r = myBeam.fit.slist[k]
if fill:
x1,y1 = myMap(fov.lonFull[myBeam.bmnum,r],fov.latFull[myBeam.bmnum,r])
x2,y2 = myMap(fov.lonFull[myBeam.bmnum,r+1],fov.latFull[myBeam.bmnum,r+1])
x3,y3 = myMap(fov.lonFull[myBeam.bmnum+1,r+1],fov.latFull[myBeam.bmnum+1,r+1])
x4,y4 = myMap(fov.lonFull[myBeam.bmnum+1,r],fov.latFull[myBeam.bmnum+1,r])
#save the polygon vertices
verts.append(((x1,y1),(x2,y2),(x3,y3),(x4,y4),(x1,y1)))
#save the param to use as a color scale
if(param == 'velocity'): intensities.append(myBeam.fit.v[k])
elif(param == 'power'): intensities.append(myBeam.fit.p_l[k])
elif(param == 'width'): intensities.append(myBeam.fit.w_l[k])
elif(param == 'elevation' and myBeam.prm.xcf): intensities.append(myBeam.fit.elv[k])
elif(param == 'phi0' and myBeam.prm.xcf): intensities.append(myBeam.fit.phi0[k])
else:
x1,y1 = myMap(fov.lonCenter[myBeam.bmnum,r],fov.latCenter[myBeam.bmnum,r])
verts[0].append(x1)
verts[1].append(y1)
x2,y2 = myMap(fov.lonCenter[myBeam.bmnum,r+1],fov.latCenter[myBeam.bmnum,r+1])
theta = math.atan2(y2-y1,x2-x1)
x2,y2 = x1+myBeam.fit.v[k]/velscl*(-1.0)*math.cos(theta)*dist,y1+myBeam.fit.v[k]/velscl*(-1.0)*math.sin(theta)*dist
lines.append(((x1,y1),(x2,y2)))
#save the param to use as a color scale
if(param == 'velocity'): intensities[0].append(myBeam.fit.v[k])
elif(param == 'power'): intensities[0].append(myBeam.fit.p_l[k])
elif(param == 'width'): intensities[0].append(myBeam.fit.w_l[k])
elif(param == 'elevation' and myBeam.prm.xcf): intensities[0].append(myBeam.fit.elv[k])
elif(param == 'phi0' and myBeam.prm.xcf): intensities[0].append(myBeam.fit.phi0[k])
if(myBeam.fit.p_l[k] > 0): intensities[1].append(myBeam.fit.p_l[k])
else: intensities[1].append(0.)
if(gsct): gs_flg.append(myBeam.fit.gflg[k])
#do the actual overlay
if(fill):
#if we have data
if(verts != []):
if(gsct == 0):
inx = numpy.arange(len(verts))
else:
inx = numpy.where(numpy.array(gs_flg)==0)
x = PolyCollection(numpy.array(verts)[numpy.where(numpy.array(gs_flg)==1)],
facecolors='.3',linewidths=0,zorder=5,alpha=alpha)
myFig.gca().add_collection(x, autolim=True)
pcoll = PolyCollection(numpy.array(verts)[inx],
edgecolors='face',linewidths=0,closed=False,zorder=4,
alpha=alpha,cmap=cmap,norm=norm)
#set color array to intensities
pcoll.set_array(numpy.array(intensities)[inx])
myFig.gca().add_collection(pcoll, autolim=True)
return intensities,pcoll
else:
#if we have data
if(verts != [[],[]]):
if(gsct == 0):
inx = numpy.arange(len(verts[0]))
else:
inx = numpy.where(numpy.array(gs_flg)==0)
#plot the ground scatter as open circles
x = myFig.scatter(numpy.array(verts[0])[numpy.where(numpy.array(gs_flg)==1)],\
numpy.array(verts[1])[numpy.where(numpy.array(gs_flg)==1)],\
s=.1*numpy.array(intensities[1])[numpy.where(numpy.array(gs_flg)==1)],\
zorder=5,marker='o',linewidths=.5,facecolors='w',edgecolors='k')
myFig.gca().add_collection(x, autolim=True)
#plot the i-s as filled circles
ccoll = myFig.gca().scatter(numpy.array(verts[0])[inx],numpy.array(verts[1])[inx], \
s=.1*numpy.array(intensities[1])[inx],zorder=10,marker='o',linewidths=.5, \
edgecolors='face',cmap=cmap,norm=norm)
#set color array to intensities
ccoll.set_array(numpy.array(intensities[0])[inx])
myFig.gca().add_collection(ccoll)
#plot the velocity vectors
lcoll = LineCollection(numpy.array(lines)[inx],linewidths=.5,zorder=12,cmap=cmap,norm=norm)
lcoll.set_array(numpy.array(intensities[0])[inx])
myFig.gca().add_collection(lcoll)
return intensities,lcoll
示例6: colorbar
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
units=var_atts[varname]['units']
data=utils.get_packed_data(dt, tsvert, dtc)
data=numpy.ma.masked_equal(data,fill_val,copy=False)
# apply the scale_factor
if scale_factor is not None:
data=data.astype(scale_factor.dtype.char)*scale_factor
# apply the add_offset
if add_offset is not None:
data+=add_offset
qvert_list=mesh.getEntAdj(quads,iBase.Type.vertex)
poly_list=[]
for qv in qvert_list:
cds=mesh.getVtxCoords(qv)
poly_list.append(cds[:,[0,1]].tolist())
pcoll=PolyCollection(poly_list, edgecolor='none')
pcoll.set_array(data)
pcoll.set_cmap(cm.jet)
a=fig.add_subplot(ncol,nrow,i)
a.add_collection(pcoll, autolim=True)
a.autoscale_view()
colorbar(pcoll,orientation='vertical')
title("%s (%s)" % (varname,units))
i+=1
show(0)
示例7: tripcolor
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def tripcolor(ax, *args, **kwargs):
"""
Create a pseudocolor plot of an unstructured triangular grid to
the :class:`~matplotlib.axes.Axes`.
The triangulation can be specified in one of two ways; either::
tripcolor(triangulation, ...)
where triangulation is a :class:`~matplotlib.tri.Triangulation`
object, or
::
tripcolor(x, y, ...)
tripcolor(x, y, triangles, ...)
tripcolor(x, y, triangles=triangles, ...)
tripcolor(x, y, mask=mask, ...)
tripcolor(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See
:class:`~matplotlib.tri.Triangulation` for a explanation of these
possibilities.
The next argument must be *C*, the array of color values, one per
point in the triangulation. The colors used for each triangle
are from the mean C of the triangle's three points.
The remaining kwargs are the same as for
:meth:`~matplotlib.axes.Axes.pcolor`.
**Example:**
.. plot:: mpl_examples/pylab_examples/tripcolor_demo.py
"""
if not ax._hold: ax.cla()
alpha = kwargs.pop('alpha', 1.0)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
shading = kwargs.pop('shading', 'flat')
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
x = tri.x
y = tri.y
triangles = tri.get_masked_triangles()
# Vertices of triangles.
verts = np.concatenate((x[triangles][...,np.newaxis],
y[triangles][...,np.newaxis]), axis=2)
C = np.asarray(args[0])
if C.shape != x.shape:
raise ValueError('C array must have same length as triangulation x and'
' y arrays')
# Color values, one per triangle, mean of the 3 vertex color values.
C = C[triangles].mean(axis=1)
if shading == 'faceted':
edgecolors = (0,0,0,1),
linewidths = (0.25,)
else:
edgecolors = 'face'
linewidths = (1.0,)
kwargs.setdefault('edgecolors', edgecolors)
kwargs.setdefault('antialiaseds', (0,))
kwargs.setdefault('linewidths', linewidths)
collection = PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None: assert(isinstance(norm, Normalize))
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim( corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection
示例8: tile
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def tile(self, x, y, w, h, color=None,
anchor='center', edgecolors='face', linewidth=0.8,
**kwargs):
"""Plot rectanguler tiles based onto these `Axes`.
``x`` and ``y`` give the anchor point for each tile, with
``w`` and ``h`` giving the extent in the X and Y axis respectively.
Parameters
----------
x, y, w, h : `array_like`, shape (n, )
Input data
color : `array_like`, shape (n, )
Array of amplitudes for tile color
anchor : `str`, optional
Anchor point for tiles relative to ``(x, y)`` coordinates, one of
- ``'center'`` - center tile on ``(x, y)``
- ``'ll'`` - ``(x, y)`` defines lower-left corner of tile
- ``'lr'`` - ``(x, y)`` defines lower-right corner of tile
- ``'ul'`` - ``(x, y)`` defines upper-left corner of tile
- ``'ur'`` - ``(x, y)`` defines upper-right corner of tile
**kwargs
Other keywords are passed to
:meth:`~matplotlib.collections.PolyCollection`
Returns
-------
collection : `~matplotlib.collections.PolyCollection`
the collection of tiles drawn
Examples
--------
>>> import numpy
>>> from matplotlib import pyplot
>>> import gwpy.plot # to get gwpy's Axes
>>> x = numpy.arange(10)
>>> y = numpy.arange(x.size)
>>> w = numpy.ones_like(x) * .8
>>> h = numpy.ones_like(x) * .8
>>> fig = pyplot.figure()
>>> ax = fig.gca()
>>> ax.tile(x, y, w, h, anchor='ll')
>>> pyplot.show()
"""
# get color and sort
if color is not None and kwargs.get('c_sort', True):
sortidx = color.argsort()
x = x[sortidx]
y = y[sortidx]
w = w[sortidx]
h = h[sortidx]
color = color[sortidx]
# define how to make a polygon for each tile
if anchor == 'll':
def _poly(x, y, w, h):
return ((x, y), (x, y+h), (x+w, y+h), (x+w, y))
elif anchor == 'lr':
def _poly(x, y, w, h):
return ((x-w, y), (x-w, y+h), (x, y+h), (x, y))
elif anchor == 'ul':
def _poly(x, y, w, h):
return ((x, y-h), (x, y), (x+w, y), (x+w, y-h))
elif anchor == 'ur':
def _poly(x, y, w, h):
return ((x-w, y-h), (x-w, y), (x, y), (x, y-h))
elif anchor == 'center':
def _poly(x, y, w, h):
return ((x-w/2., y-h/2.), (x-w/2., y+h/2.),
(x+w/2., y+h/2.), (x+w/2., y-h/2.))
else:
raise ValueError("Unrecognised tile anchor {!r}".format(anchor))
# build collection
cmap = kwargs.pop('cmap', rcParams['image.cmap'])
coll = PolyCollection((_poly(*tile) for tile in zip(x, y, w, h)),
edgecolors=edgecolors, linewidth=linewidth,
**kwargs)
if color is not None:
coll.set_array(color)
coll.set_cmap(cmap)
out = self.add_collection(coll)
self.autoscale_view()
return out
示例9: plotCurrent
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def plotCurrent(self, dtfrom, fnamebase):
#self.figure.clf()
#self.canvas.draw()
#self.loadModel()
self.progressBar.setValue(51)
frmDate = self.dtFrom.dateTime()
#print 'Plotting till date: ' + dtfrom.date().toString()
# get velocity nearest to current time
##dtnow = dt.datetime.utcnow() + dt.timedelta(hours=0)
day = dtfrom.date().day()
month = dtfrom.date().month()
year = dtfrom.date().year()
hour = dtfrom.time().hour()
minute = dtfrom.time().minute()
second = dtfrom.time().second()
msecond = dtfrom.time().msec()
#print dir(dtnow)
#print dtnow.time()
startdt = dt.datetime(year, month, day, hour, minute, second, msecond)
#print startdt
#print start
istart = netCDF4.date2index(startdt,self.time_var,select=self.interp_method)
layer = 0 # surface layer
u = self.nc.variables[self.uvar][istart, layer, :]
v = self.nc.variables[self.vvar][istart, layer, :]
mag = numpy.sqrt((u*u)+(v*v))
#print start
#print istart
self.progressBar.setValue(63)
# Now try plotting speed and vectors with Basemap using a PolyCollection
m = Basemap(projection='merc', llcrnrlat=self.lat.min(), urcrnrlat=self.lat.max(),
llcrnrlon=self.lon.min(), urcrnrlon=self.lon.max(),
lat_ts=self.lat.mean(), resolution=None)
# project from lon,lat to mercator
xnode, ynode = m(self.lon, self.lat)
xc, yc = m(self.lonc, self.latc)
nv = self.nc.variables[self.nvvar][:].T - 1
# create a TRI object with projected coordinates
tri = Tri.Triangulation(xnode, ynode, triangles=nv)
self.progressBar.setValue(77)
sig_lay = self.nc.variables['siglay']
zeta = self.nc.variables['zeta']
# make a PolyCollection using triangles
verts = concatenate((tri.x[tri.triangles][..., None],
tri.y[tri.triangles][..., None]), axis=2)
colorlut = []
fid = 0
for poly in verts:
fid = fid + 1
collection = PolyCollection(verts)
collection.set_edgecolor('none')
self.progressBar.setValue(81)
timestamp=startdt.strftime('%Y-%m-%d %H:%M:%S')
# set the magnitude of the polycollection to the speed
collection.set_array(mag)
#sys.exit(1)
collection.norm.vmin=0
collection.norm.vmax=0.5
#for path in collection.get_paths():
cmap =collection.cmap
featurecount = fid
redArray = matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['red'], 1.0)
greenArray = matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['green'], 1.0)
blueArray = matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['blue'], 1.0)
fid = 0
for path in collection.get_paths():
tricolor = self.makehexcolor(redArray[fid], greenArray[fid], blueArray[fid])
##print tricolor
#.........这里部分代码省略.........
示例10: __main__
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
def __main__( request, actions, u, v, width, height, lonmax, lonmin, latmax, latmin, index, lon, lat, lonn, latn, nv):
fig = Plot.figure(dpi=150, facecolor='none', edgecolor='none')
fig.set_alpha(0)
#ax = fig.add_subplot(111)
projection = request.GET["projection"]
m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin,
urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection,
#lat_0 =(latmax + latmin) / 2, lon_0 =(lonmax + lonmin) / 2,
lat_ts = 0.0,
)
#lonn, latn = m(lonn, latn)
m.ax = fig.add_axes([0, 0, 1, 1])
#fig.set_figsize_inches((20/m.aspect, 20.))
fig.set_figheight(5)
fig.set_figwidth(5/m.aspect)
if "regrid" in actions:
#import fvcom_compute.fvcom_stovepipe.regrid as regrid
#wid = numpy.max((width, height))
#size = (lonmax - lonmin) / wid
#hi = (latmax - latmin) / size
#hi = math.ceil(hi)
#reglon = numpy.linspace(numpy.negative(lonmin), numpy.negative(lonmax), wid)
#reglon = numpy.negative(reglon)
#reglat = numpy.linspace(latmin, latmax, hi)
#if "pcolor" in actions:
# mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2)
# mag = numpy.sqrt(mag)
# newvalues = regrid.regrid(mag, lonn, latn, nv, reglon, reglat, size)
# reglon, reglat = numpy.meshgrid(reglon, reglat)
# grid = reorderArray(newvalues, len(reglat[:,1]), len(reglon[1,:]))
# ax = fig.add_subplot(111)
# ax.pcolor(reglon, reglat, grid)
#if "contours" in actions:
# mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2)
# mag = numpy.sqrt(mag)
# newvalues = regrid.regrid(mag, lonn, latn, nv, reglon, reglat, size)
# reglon, reglat = numpy.meshgrid(reglon, reglat)
# grid = reorderArray(newvalues, len(reglat[:,1]), len(reglon[1,:]))
# ax = fig.add_subplot(111)
# ax.contourf(reglon, reglat, grid)
#if "vectors" in actions:
# newv = regrid.regrid(v, lonn, latn, nv, reglon, reglat, size)
# newu = regrid.regrid(u, lonn, latn, nv, reglon, reglat, size)
# mag = numpy.power(newu.__abs__(), 2)+numpy.power(newv.__abs__(), 2)
# mag = numpy.sqrt(mag)
# ax = fig.add_subplot(111)
# ax.quiver(reglon, reglat, newu, newv, mag, pivot='mid')
pass
else:
if "vectors" in actions:
mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2)
mag = numpy.sqrt(mag)
#ax = fig.add_subplot(111)
#ax.quiver(lon, lat, u, v, mag, pivot='mid')
lon, lat = m(lon, lat)
m.quiver(lon, lat, u, v, mag, pivot='mid')
ax = Plot.gca()
elif "contours" in actions:
mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2)
mag = numpy.sqrt(mag)
ax = fig.add_subplot(111)
ax.tricontourf(lon, lat, mag)
elif "facets" in actions:
#projection = request.GET["projection"]
#m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin,
# urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection,
# lat_0 =(latmax + latmin) / 2, lon_0 =(lonmax + lonmin) / 2,
# )
lonn, latn = m(lonn, latn)
#m.ax = fig.add_axes([0, 0, 1, 1])
#fig.set_figheight(20)
#fig.set_figwidth(20/m.aspect)
#m.drawmeridians(numpy.arange(0,360,1), color='0.5',)
tri = Tri.Triangulation(lonn,latn,triangles=nv)
mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2)
mag = numpy.sqrt(mag)
#ax.tripcolor(lon, lat, mag, shading="")
#collection = PolyCollection(numpy.asarray([(lonn[node1],latn[node1]),(lonn[node2],latn[node2]),(lonn[node3],latn[node3])]))
verts = numpy.concatenate((tri.x[tri.triangles][...,numpy.newaxis],\
tri.y[tri.triangles][...,numpy.newaxis]), axis=2)
collection = PolyCollection(verts)
collection.set_array(mag)
collection.set_edgecolor('none')
ax = Plot.gca()
#m.add_collection(collection)
#ax = Plot.gca()
#m2.ax.add_collection(collection)
ax.add_collection(collection)
lonmax, latmax = m(lonmax, latmax)
lonmin, latmin = m(lonmin, latmin)
ax.set_xlim(lonmin, lonmax)
ax.set_ylim(latmin, latmax)
ax.set_frame_on(False)
#.........这里部分代码省略.........
示例11: overlayFan
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
#.........这里部分代码省略.........
elif(param == 'width'):
intensities.append(myBeam.fit.w_l[k])
elif(param == 'elevation' and myBeam.prm.xcf):
intensities.append(myBeam.fit.elv[k])
elif(param == 'phi0' and myBeam.prm.xcf):
intensities.append(myBeam.fit.phi0[k])
else:
x1, y1 = myMap(fov.lonCenter[myBeam.bmnum, r],
fov.latCenter[myBeam.bmnum, r])
verts[0].append(x1)
verts[1].append(y1)
x2, y2 = myMap(fov.lonCenter[myBeam.bmnum, r + 1],
fov.latCenter[myBeam.bmnum, r + 1])
theta = math.atan2(y2 - y1, x2 - x1)
x2, y2 = x1 + myBeam.fit.v[k] / velscl * (-1.0) * \
math.cos(theta) * dist, y1 + myBeam.fit.v[k] / velscl * \
(-1.0) * math.sin(theta) * dist
lines.append(((x1, y1), (x2, y2)))
# save the param to use as a color scale
if(param == 'velocity'):
intensities[0].append(myBeam.fit.v[k])
elif(param == 'power'):
intensities[0].append(myBeam.fit.p_l[k])
elif(param == 'width'):
intensities[0].append(myBeam.fit.w_l[k])
elif(param == 'elevation' and myBeam.prm.xcf):
intensities[0].append(myBeam.fit.elv[k])
elif(param == 'phi0' and myBeam.prm.xcf):
intensities[0].append(myBeam.fit.phi0[k])
if(myBeam.fit.p_l[k] > 0):
intensities[1].append(myBeam.fit.p_l[k])
else:
intensities[1].append(0.)
if(gsct):
gs_flg.append(myBeam.fit.gflg[k])
# do the actual overlay
if(fill):
# if we have data
if(verts != []):
if(gsct == 0):
inx = numpy.arange(len(verts))
else:
inx = numpy.where(numpy.array(gs_flg) == 0)
x = PolyCollection(numpy.array(verts)[numpy.where(
numpy.array(gs_flg) == 1)], facecolors='.3',
linewidths=0, zorder=5, alpha=alpha)
myFig.gca().add_collection(x, autolim=True)
pcoll = PolyCollection(numpy.array(verts)[inx],
edgecolors='face', linewidths=0,
closed=False, zorder=4, alpha=alpha,
cmap=cmap, norm=norm)
# set color array to intensities
pcoll.set_array(numpy.array(intensities)[inx])
myFig.gca().add_collection(pcoll, autolim=True)
return intensities, pcoll
else:
# if we have data
if(verts != [[], []]):
if(gsct == 0):
inx = numpy.arange(len(verts[0]))
else:
inx = numpy.where(numpy.array(gs_flg) == 0)
# plot the ground scatter as open circles
x = myFig.scatter(numpy.array(verts[0])[numpy.where(
numpy.array(gs_flg) == 1)],
numpy.array(verts[1])[numpy.where(
numpy.array(gs_flg) == 1)],
s=.1 * numpy.array(intensities[1])[
numpy.where(numpy.array(gs_flg) == 1)],
zorder=5, marker='o', linewidths=.5,
facecolors='w', edgecolors='k')
myFig.gca().add_collection(x, autolim=True)
# plot the i-s as filled circles
ccoll = myFig.gca().scatter(numpy.array(verts[0])[inx],
numpy.array(verts[1])[inx],
s=.1 * numpy.array(
intensities[1])[inx], zorder=10,
marker='o', linewidths=.5,
edgecolors='face', cmap=cmap,
norm=norm)
# set color array to intensities
ccoll.set_array(numpy.array(intensities[0])[inx])
myFig.gca().add_collection(ccoll)
# plot the velocity vectors
lcoll = LineCollection(numpy.array(lines)[inx], linewidths=.5,
zorder=12, cmap=cmap, norm=norm)
lcoll.set_array(numpy.array(intensities[0])[inx])
myFig.gca().add_collection(lcoll)
return intensities, lcoll
示例12: dict
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
ni = ncv['nodeid'][:]
xdict = dict(zip(ni,x))
ydict = dict(zip(ni,y))
s = ncv['hzg_ecosmo_sed2'][:]
nv = ncv['nv'][:,:3]-1
verts=[]
for nvi in nv:
verts.append([(xdict[i+1],ydict[i+1]) for i in nvi])
verts=asarray(verts)
f=figure(figsize=(10,10))
p = PolyCollection(verts,closed=True,edgecolor='none')
p.set_array(s[0])
p.set_cmap(cm.RdYlBu_r)
pn = PolyCollection(verts,closed=True,edgecolor='none')
pn.set_array(arange(len(s[0])))
pn.set_cmap(cm.RdYlBu_r)
ax=axes([0.1,0.75,0.88,0.2])
ax.add_collection(p,autolim=True)
autoscale()
colorbar(p)
ax=axes([0.1,0.25,0.88,0.2])
ax.add_collection(pn,autolim=True)
autoscale()
colorbar(pn)
示例13: __init__
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
#.........这里部分代码省略.........
# coords = metadata['coords']
#
if coords not in ['gate','range']:
print 'Coords "%s" not supported for RTI plots. Using "gate".' % coords
coords = 'gate'
if coords == 'gate':
rnge = currentData.fov.gates
elif coords == 'range':
rnge = currentData.fov.slantRFull[beam,:]
xvec = [matplotlib.dates.date2num(x) for x in currentData.time]
for tm in range(nrTimes-1):
for rg in range(nrGates-1):
if np.isnan(data[tm,rg]): continue
if data[tm,rg] == 0 and not plotZeros: continue
scan.append(data[tm,rg])
x1,y1 = xvec[tm+0],rnge[rg+0]
x2,y2 = xvec[tm+1],rnge[rg+0]
x3,y3 = xvec[tm+1],rnge[rg+1]
x4,y4 = xvec[tm+0],rnge[rg+1]
verts.append(((x1,y1),(x2,y2),(x3,y3),(x4,y4),(x1,y1)))
if (cmap_handling == 'matplotlib') or autoScale:
cmap = matplotlib.cm.jet
bounds = np.linspace(scale[0],scale[1],256)
norm = matplotlib.colors.BoundaryNorm(bounds,cmap.N)
elif cmap_handling == 'superdarn':
colors = 'lasse'
cmap,norm,bounds = utils.plotUtils.genCmap(param,scale,colors=colors)
pcoll = PolyCollection(np.array(verts),edgecolors='face',linewidths=0,closed=False,cmap=cmap,norm=norm,zorder=99)
pcoll.set_array(np.array(scan))
axis.add_collection(pcoll,autolim=False)
# Plot the terminator! #########################################################
if plotTerminator:
# print 'Terminator functionality is disabled until further testing is completed.'
term_verts = []
term_scan = []
rnge = currentData.fov.gates
xvec = [matplotlib.dates.date2num(x) for x in currentData.time]
for tm in range(nrTimes-1):
for rg in range(nrGates-1):
if daylight[tm,rg]: continue
term_scan.append(1)
x1,y1 = xvec[tm+0],rnge[rg+0]
x2,y2 = xvec[tm+1],rnge[rg+0]
x3,y3 = xvec[tm+1],rnge[rg+1]
x4,y4 = xvec[tm+0],rnge[rg+1]
term_verts.append(((x1,y1),(x2,y2),(x3,y3),(x4,y4),(x1,y1)))
term_pcoll = PolyCollection(np.array(term_verts),facecolors='0.45',linewidth=0,zorder=99,alpha=0.25)
axis.add_collection(term_pcoll,autolim=False)
################################################################################
if axvlines is not None:
for line in axvlines:
axis.axvline(line,color=axvline_color,ls='--')
if xlim == None:
xlim = (np.min(time),np.max(time))
axis.set_xlim(xlim)
示例14: concatenate
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
tri = Tri.Triangulation(xnode, ynode, triangles=nv)
# make a PolyCollection using triangles
verts = concatenate((tri.x[tri.triangles][..., None],
tri.y[tri.triangles][..., None]), axis=2)
collection = PolyCollection(verts)
collection.set_edgecolor('none')
# <codecell>
timestamp=start.strftime('%Y-%m-%d %H:%M:%S')
# <codecell>
# set the magnitude of the polycollection to the speed
collection.set_array(mag)
collection.norm.vmin=0
collection.norm.vmax=0.5
# <codecell>
fig = plt.figure(figsize=(12,12))
ax=fig.add_subplot(111)
m.drawmapboundary(fill_color='0.3')
#m.drawcoastlines()
#m.fillcontinents()
# add the speed as colored triangles
ax.add_collection(collection) # add polygons to axes on basemap instance
# add the vectors
Q = m.quiver(xc,yc,u,v,scale=30)
# add a key for the vectors
示例15: _gen2d3d
# 需要导入模块: from matplotlib.collections import PolyCollection [as 别名]
# 或者: from matplotlib.collections.PolyCollection import set_array [as 别名]
#.........这里部分代码省略.........
elif kind == 'waterfall':
edgecolors = pltkwargs.setdefault('edgecolors', None)
pltkwargs.setdefault('closed', False)
alpha = pltkwargs.setdefault('alpha', None)
# Need to handle cmap/colors a bit differently for PolyCollection API
if 'color' in pltkwargs:
pltkwargs['facecolors']=pltkwargs.pop('color')
cmap = pltkwargs.setdefault('cmap', None)
if alpha is None: #as opposed to 0
alpha = 0.6 * (13.0/ts.shape[1])
if alpha > 0.6:
alpha = 0.6
#Delete stride keywords
for key in ['cstride', 'rstride']:
try:
del pltkwargs[key]
except KeyError:
pass
# Verts are index dotted with data
verts = []
for col in ts.columns:
values = ts[col]
values[0], values[-1] = values.min().min(), values.min().min()
verts.append(list(zip(ts.index, values)))
mappable = PolyCollection(verts, **pltkwargs)
if cmap:
mappable.set_array(cols) #If set array in __init__, autogens a cmap!
mappable.set_cmap(pltkwargs['cmap'])
mappable.set_alpha(alpha)
#zdir is the direction used to plot; dont' fully understand
ax.add_collection3d(mappable, zs=cols, zdir='x' )
# custom limits/labels polygon plot (reverse x,y)
if not ylim:
ylim = (max(index), min(index)) #REVERSE AXIS FOR VIEWING PURPOSES
if not xlim:
xlim = (min(cols), max(cols)) #x
if not zlim:
zlim = (min(ts.min()), max(ts.max())) #How to get absolute min/max of ts values
# Reverse labels/DTI call for correct orientaion HACK HACK HACK
xlabel, ylabel = ylabel, xlabel
_x_dti, _y_dti = _y_dti, _x_dti
azim = -1 * azim
# General Features
# ----------------
# Some applications (like add_projection) shouldn't alther axes features
if not _modifyax:
return (ax, mappable)
if cbar:
# Do I want colorbar outside of fig? Wouldn't be better on axes?
try: