本文整理汇总了Python中matplotlib.collections.PatchCollection.set_array方法的典型用法代码示例。如果您正苦于以下问题:Python PatchCollection.set_array方法的具体用法?Python PatchCollection.set_array怎么用?Python PatchCollection.set_array使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.PatchCollection
的用法示例。
在下文中一共展示了PatchCollection.set_array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_patches
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plot_patches(self, x_range, y_range, file_name="voronoi_p1.png"):
t0=time.time()
self.run()
print((time.time()-t0))
pts = self.sites
pts_dict = defaultdict(list)
patches = []
colors = []
for edge in self.edges:
pts_dict[edge.pl].append((edge.start, edge.end))
pts_dict[edge.pr].append((edge.start, edge.end))
for center, v_raw in pts_dict.items():
starts, ends = zip(*v_raw)
vertices = set(starts + ends)
vertices = sorted(vertices, key=lambda p: np.arctan2(p.y-center.y,p.x-center.x))
vertices = [(v.x, v.y) for v in vertices]
patches.append(Polygon(vertices, True))
colors.append(center.dist_to_point(Point(0,0)))
fig, ax = plt.subplots()
colors = 100*np.random.rand(len(patches))
pc = PatchCollection(patches, cmap=jet, alpha=0.2)
pc.set_array(np.array(colors))
ax.axis([*x_range, *y_range])
ax.add_collection(pc)
ax.margins(0.1)
xs, ys = zip(*[(p.x, p.y) for p in pts])
ax.plot(xs, ys, 'ro', markersize=1)
fig.savefig(file_name)
示例2: drawboxes
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def drawboxes(breaks, axis, boxcolor=1):
'''Draws boxes on the current plot.'''
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
ax = plt.gca()
x1, x2 = plt.xlim()
y1, y2 = plt.ylim()
patches = []
if axis == 0:
for i in range(len(breaks) - 1):
y1, y2 = (breaks[i + 1], breaks[i])
patches.append(
Polygon([[x1, y2], [x1, y1], [x2, y1], [x2, y2]], True))
else:
for i in range(len(breaks) - 1):
x1, x2 = (breaks[i + 1], breaks[i])
patches.append(
Polygon([[x1, y2], [x1, y1], [x2, y1], [x2, y2]], True))
if boxcolor == 1:
p = PatchCollection(patches, cmap=plt.cm.jet, alpha=0.4)
else:
p = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.2)
p.set_array(np.array([0, 0.2, 0.4, 0.5, 0.7, 0.9, 1]))
ax.add_collection(p)
示例3: plot_
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plot_(pnts):
"""plot a circle, arc sector etc
"""
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
#x_min = pnts[:,0].min()
#x_max = pnts[:,0].max()
#y_min = pnts[:,1].min()
#y_max = pnts[:,1].max()
fig, ax = plt.subplots()
patches = []
# Points need to form a closed loopset closed to True if your 1st and
# last pnt aren't equal.
for i in pnts:
polygon = Polygon(i, closed=False)
patches.append(polygon)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
colors = 100*np.random.rand(len(patches))
p.set_array(np.array(colors))
#ax.set_xlim(x_min-0.5, x_max+0.5) # (x_min, x_max)
#ax.set_ylim(y_min-0.5, y_max+0.5) # y_min, y_max)
ax.add_collection(p)
plt.axis('equal')
plt.show()
示例4: circles
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
if np.isscalar(c):
kwargs.setdefault('color', c)
c = None
if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))
patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
collection = PatchCollection(patches, **kwargs)
if c is not None:
collection.set_array(np.asarray(c))
collection.set_clim(vmin, vmax)
ax = plt.gca()
ax.add_collection(collection)
ax.autoscale_view()
if c is not None:
plt.sci(collection)
return collection
示例5: animate_path
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def animate_path(self, path, key_xy):
fig, ax = plt.subplots()
colors = 100*np.random.rand(len(self.plot_obstacles_polygon))
p = PatchCollection(self.plot_obstacles_polygon, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(np.array(colors))
ax.add_collection(p)
plt.colorbar(p)
plt.plot([self.initial_state[0]], [self.initial_state[1]], 'bs', self.goal_state[0], self.goal_state[1], 'g^')
plt.axis([0, self.resolution, 0, self.resolution])
x_0, y_0 = key_xy(path[0])[0], key_xy(path[0])[1]
x_1, y_1 = key_xy(path[0 + 1])[0], key_xy(path[0 + 1])[1]
dx, dy = x_1 - x_0, y_0 - y_1
qv = ax.quiver(x_0, y_0, dx, dy, angles='xy',scale_units='xy',scale=1)
def animate(i):
x_init, y_init =key_xy(path[i])[0], key_xy(path[i])[1]
x_f, y_f = key_xy(path[i + 1])[0], key_xy(path[i + 1])[1]
dx, dy = x_f - x_init, y_f - y_init
qv.set_UVC(np.array(dx), np.array(dy))
qv.set_offsets((x_init, y_init))
return qv
anim = animation.FuncAnimation(fig, animate, frames=range(0, len(path)-1), interval=500)
plt.show()
示例6: get_circles_for_scatter
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def get_circles_for_scatter(x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
cmap = plt.get_cmap(colormap)
if colornorm is not None:
colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
# setup normalizing for radius scale factor (if used)
if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
if radiusnorm is None:
radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
else:
radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)
# make circles
points = np.array([x, y]).T
circles = [None for i in range(len(x))]
for i, pt in enumerate(points):
if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
else:
r = radius
circles[i] = patches.Circle( pt, radius=r )
# make a collection of those circles
cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
# set properties for collection
cc.set_edgecolors(edgecolor)
if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
cc.set_array(color)
else:
cc.set_facecolors(color)
cc.set_alpha(alpha)
return cc
示例7: plotGrid
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plotGrid(verbose=True, save=False, show=True, dpi=300):
'''Show Dymaxion Grid'''
plt.figure(figsize=(20,12))
patches = []
for zdx, vertset in enumerate(constants.vert_indices):
if zdx==8 or zdx==15: continue # Edge Triangles
x,y = [],[]
for i,vert in enumerate(vertset):
xt,yt = convert.vert2dymax(vert,vertset)
#print(xt,yt)
x += [xt]
y += [yt]
#print(xt,yt,i,vert)
#plt.plot(x,y,'k',lw=.1)
patches.append(Polygon(np.array([x,y]).T,closed=False, fill=True))
colors = 100*np.random.random(len(patches))
p = PatchCollection(patches, cmap=plt.cm.jet, alpha=1,linewidths=0.)
p.set_array(np.array(colors))
plt.gca().add_collection(p)
if verbose: print(':: plotted',len(patches),'coastlines')
plt.gca().set_aspect('equal')
plt.gca().set_xlim([0,5.5])
plt.gca().set_ylim([0,2.6])
plt.gca().get_xaxis().set_visible(False)
plt.gca().get_yaxis().set_visible(False)
plt.gca().axis('off')
if save: plt.savefig('dymax_grid.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
if show:
plt.tight_layout()
plt.show()
else: plt.close()
示例8: plotRectilinearTriangles
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plotRectilinearTriangles(verbose=True, save=False, show=True, dpi=300, resolution='c'):
lonlat_islands, dymax_islands = getIslands(resolution)
plt.figure(figsize=(20,12))
plt.title('The dymax face polygons look super-fucked on a rectilinear projection')
patches = []
faces = []
for island in lonlat_islands:
polygon = Polygon(np.array(island),closed=False, fill=True)
patches.append(polygon)
for face in range(constants.facecount):
derp = np.zeros((3,2))
for vtex in range(3):
derp[vtex] = constants.lon_lat_verts[constants.vert_indices[face,vtex]]
polygon = Polygon(derp,closed=False,fill=True)
faces.append(polygon)
colors = 100*np.random.random(len(patches))
p = PatchCollection(patches, cmap=plt.cm.jet, alpha=0.7,linewidths=0.)
f = PatchCollection(faces, cmap=plt.cm.jet, alpha=0.3,linewidths=1.)
p.set_array(np.array(colors))
f.set_array(np.array(colors))
plt.gca().add_collection(p)
plt.gca().add_collection(f)
if verbose: print(':: plotted',len(patches),'coastlines')
plt.xlim(-180,180)
plt.ylim(-90,90)
if save: plt.savefig('dymax_rectilineartriangles.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
if show:
plt.tight_layout()
plt.show()
else: plt.close()
示例9: plot_Vexons
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plot_Vexons(self, ybar, Vbar, fig, ax):
x=1
width=5
patches=[]
y=ybar
cnt=0
for p in Vbar:
x= p[0]-xstart
width= p[1] - p[0]
print x, width
rect= Rectangle( (x,y), width, self.height )
patches.append(rect)
epsilon=-0.35
"""
ax.annotate(self.exonLabels[cnt], (x+(width)/2.,y-epsilon),
fontsize=10, ha='center', va='center')
"""
cnt+=1
colors = 100*np.random.rand(len(patches))
q = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.6)
q.set_array(np.array(colors))
ax.add_collection(q)
ax.set_xlim([self.xLower, self.xUpper])
ax.set_ylim([4, 6])
示例10: plot_single_circle_grid
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plot_single_circle_grid(centroids, radiuses, ax, intensities, grid=True, alpha=0.75):
# intensities = np.ma.masked_equal(abs(np.array(intensities)), .0)
patches = []
count = 0
if grid:
for n, x in enumerate(centroids):
for y, r in zip(centroids, radiuses):
# ax.text(x, y, count)
count += 1
circle = Circle((x, y), r)
patches.append(circle)
else:
for xy, r in zip(centroids, radiuses):
count += 1
circle = Circle(xy, r)
patches.append(circle)
sorted_index = [idx for (intensity, idx) in sorted(zip(intensities, range(len(intensities))))]
patches = [patches[idx] for idx in sorted_index]
intensities = [intensities[idx] for idx in sorted_index]
norm = mpl.colors.Normalize(vmin=0.0, vmax=max(intensities))
cm.jet.set_bad(color='white', alpha=0.0)
colors = [('white')] + [(cm.jet(i)) for i in xrange(1, 256)]
new_map = mpl.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
p = PatchCollection(patches, cmap=new_map, alpha=alpha, norm=norm, linewidth=0)
p.set_array(np.array(intensities))
ax.add_collection(p)
ax.annotate(int(np.sqrt(count)), xy=(2, 90), fontsize=30,
path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")])
示例11: matrix_figure
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def matrix_figure(N1=160, N2=32):
r=0.4
fsx=20.
fsy=fsx*N2/N1
f=Figure(figsize=(fsx,fsy),frameon=False)
#f=plt.figure(figsize=(fsx,fsy),frameon=False)
ax=f.add_subplot(111,axisbg='k')
ax.set_xlim([-2*r,N1-1+2*r])
ax.set_ylim([-2*r,N2-1+2*r])
ax.set_axis_bgcolor('k')
ax.set_yticks([])
ax.set_xticks([])
ax.set_frame_on(False)
x=np.arange(N1)
y=np.arange(N2)
xx,yy=np.meshgrid(x,y)
cmap = col.ListedColormap([ '#6E6E6E','#FE2E2E', '#64FE2E', '#FF8000'])
colors=np.random.randint(0,4,(N1,N2))
patches = []
for x1,y1 in zip(xx.flatten(), yy.flatten()):
circle = Circle((x1,y1), r)
patches.append(circle)
p = PatchCollection(patches, cmap=cmap)
p.set_array(colors.flatten())
ax.add_collection(p)
f.subplots_adjust(0,0,1,1)
return ax, colors
示例12: plotshapefile
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plotshapefile(shpfile, colorlist):
fig, ax = plt.subplots()
#shpfile = 'C:/_DATA/CancerData/SatScan/NorthEasternUS.shp'
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
#records = np.array(sf.records())
[x1, y1, x2, y2] = find_bounding_box(shpfile)
patches = []
for shape in shapes:
lons,lats = zip(*shape.points)
data = np.array([lons, lats]).T
polygon = Polygon(data, True)
patches.append(polygon)
#colors = 100*np.random.rand(len(patches))
#colors = normalize(records[:,-3].astype(np.int32))
c#olors = records[:,-3].astype(np.int32)
colors = colorlist
p = PatchCollection(patches, cmap=cm.OrRd, alpha=0.8)
p.set_array(np.array(colors))
ax.add_collection(p)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
plt.colorbar(p)
#plt.savefig('tutorial10.png',dpi=300)
plt.show()
示例13: _setup
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def _setup(self):
# "Cheat" to see 2D map of collision data
patches = []
if isinstance(self.environment, Environment_Simulator):
for obj in self.environment.get_objects():
patch = self._create_patch(obj)
if patch is not None:
patches.append(patch)
p = None
if len(patches) > 0:
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
patch_colors = 50*np.ones(len(patches))
p.set_array(np.array(patch_colors))
self.plot_polygons = p
self.arrow_options = {
"arrowstyle": "->",
"linewidth": 2,
"alpha": 0.5
}
self.plt = plt
self.fig, self.ax = self.plt.subplots()
# Set up interactive drawing of the memory map. This makes the
# dronekit/mavproxy fairly annoyed since it creates additional
# threads/windows. One might have to press Ctrl-C and normal keys to
# make the program stop.
self.plt.gca().set_aspect("equal", adjustable="box")
if self.interactive:
self.plt.ion()
self.plt.show()
示例14: draw
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def draw(self, colorbars=True, **kwargs):
self.cbars = []
for coll, cmap, label in zip(self.collections, self.cmaps, self.cbar_labels):
pc = PatchCollection(coll, cmap=cmap)
pc.set_array(np.array([ p.value for p in coll ]))
self._ax.add_collection(pc)
if colorbars:
options = {
'orientation':'horizontal',
'pad':0.05, 'aspect':60
}
options.update(kwargs.get('colorbar-options', {}))
cbar = plt.colorbar(pc, **options)
cbar.set_label(label)
self.cbars.append(cbar)
fontdict = kwargs.get('font', {'color':'white'})
for s in self.squares:
if not s.label:
continue
x = s.x + s.dx/2
y = s.y + s.dy/2
self._ax.text(x, y, s.label, ha='center',
va='center',
fontdict=fontdict)
if self.guide_square:
self.guide_square.set_labels(self.labels)
pc = PatchCollection(self.guide_square.patches, match_original=True)
self._ax.add_collection(pc)
self._ax.autoscale_view()
示例15: plot_evolution
# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_array [as 别名]
def plot_evolution():
N = ff.current_generation
M = ff.generation_size
fig, ax = plt.subplots(figsize=(20, 20))
grid = np.mgrid[0.1:0.9:complex(0, N), 0.1:0.9:complex(0, M)].T
patches = []
colors = []
line_color = {'replace_by_other': 'green', 'replace_by_random': 'cyan', 'promoted': 'black', 'duplicate': 'orange'}
dx = 0.01
for j in range(N):
dup_dx = 0.5 * dx
for i in range(M):
entry_id = ff.lineage[str(i)][j]
nres2 = ff.population.get_entry(entry_id, {'properties.nres2': 1})['properties']['nres2']
if nres2 < 1E14:
lw = 1
ls = 'solid'
else:
lw = 1
ls = 'dotted'
if ff.population.is_evaluated(entry_id):
colors.append(ff.population.value(entry_id))
circle = mpatches.Circle(grid[i, j], 0.4 / float(M), ec="black", linewidth=lw, linestyle=ls)
patches.append(circle)
label(grid[i, j], "%7.2f" % ff.population.value(entry_id), 0.0)
for ichange in ff.population.pcdb.db.generation_changes.find({'from': entry_id, 'generation': j}):
if ichange['change'] == 'duplicate':
orig = ichange['from']
dest = ichange['to']
newi = int(ff.lineage_inv[dest])
dup_dx += dx/10.0
x, y = np.array([[grid[i, j][0] - 1.5 * dup_dx, grid[i, j][0] - 2 * dup_dx,
grid[newi, j][0] - 2 * dup_dx, grid[newi, j][0] - dx],
[grid[i, j][1], grid[i, j][1], grid[newi, j][1], grid[newi, j][1]]])
line = mlines.Line2D(x, y, lw=1., alpha=0.8, color=line_color[ichange['change']],
marker='>', markersize=5, markeredgecolor='none')
line.set_markevery([3])
ax.add_line(line)
elif j < N - 1:
x, y = np.array(
[[grid[i, j][0] + dx, grid[i, j + 1][0] - 2 * dx], [grid[i, j][1], grid[i, j + 1][1]]])
line = mlines.Line2D(x, y, lw=5., alpha=0.3, color=line_color[ichange['change']])
# label(0.5*(grid[i, j]+grid[i, j+1]), ichange['change'], 0.0)
ax.add_line(line)
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.axis('equal')
plt.axis('off')
plt.savefig(figname+'_evo.pdf')