本文整理汇总了Python中matplotlib.collections.PatchCollection类的典型用法代码示例。如果您正苦于以下问题:Python PatchCollection类的具体用法?Python PatchCollection怎么用?Python PatchCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PatchCollection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: drawboxes
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)
开发者ID:MG-RAST,项目名称:kmerspectrumanalyzer,代码行数:25,代码来源:ksatools.py
示例2: plot_patches
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)
开发者ID:vabite,项目名称:Fortune-Beach,代码行数:28,代码来源:voronoi_fortune.py
示例3: circles
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
开发者ID:Gabs48,项目名称:SpringMassNetworks,代码行数:26,代码来源:utils.py
示例4: plot_
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()
开发者ID:Dan-Patterson,项目名称:GIS,代码行数:26,代码来源:split_by_sector.py
示例5: plot_evolution
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')
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:60,代码来源:OrbitalDFTU_Plot.py
示例6: plot_Vexons
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])
开发者ID:dnolivieri,项目名称:MResVgene,代码行数:29,代码来源:plotMHCexons01.py
示例7: show_uboxes
def show_uboxes(uboxes,S=None,col='b',ecol='k', fig=None):
if uboxes.dim != 2:
raise Exception("show_uboxes: dimension must be 2")
if S is None:
S = range(uboxes.size)
patches = []
for i in S:
art = mpatches.Rectangle(uboxes.corners[i],uboxes.width[0],uboxes.width[1])
patches.append(art)
if not fig:
fig = plt.figure()
ax = fig.gca()
ax.hold(True)
collection = PatchCollection(patches)
collection.set_facecolor(col)
collection.set_edgecolor(ecol)
ax.add_collection(collection,autolim=True)
ax.autoscale_view()
plt.draw()
plt.show()
return fig
开发者ID:caosuomo,项目名称:rads,代码行数:25,代码来源:gfx.py
示例8: animate_path
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()
开发者ID:spuran91,项目名称:IntelligentSystems,代码行数:27,代码来源:Config.py
示例9: plot_refexons
def plot_refexons(self, fig, ax):
x=1
width=5
patches=[]
y=5.0
cnt=0
for p in self.exons:
x= p[0]-xstart
width= p[1] - p[0]
print x, width
rect= Rectangle( (x,y), width, self.height )
patches.append(rect)
epsilon=-0.25
ax.annotate(self.exonLabels[cnt], (x+(width)/2., y-(self.height/2.+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)
开发者ID:dnolivieri,项目名称:MResVgene,代码行数:25,代码来源:plotMHCexons01.py
示例10: data2fig
def data2fig(data, X, options, legend_title, xlabel, ylabel=r'Reachability~$\reachability$'):
if options['grayscale']:
colors = options['graycm'](pylab.linspace(0, 1, len(data.keys())))
else:
colors = options['color'](pylab.linspace(0, 1, len(data.keys())))
fig = MyFig(options, figsize=(10, 8), xlabel=r'Sources~$\sources$', ylabel=ylabel, grid=False, aspect='auto', legend=True)
for j, nhdp_ht in enumerate(sorted(data.keys())):
d = data[nhdp_ht]
try:
mean_y = [scipy.mean(d[n]) for n in X]
except KeyError:
logging.warning('key \"%s\" not found, continuing...', nhdp_ht)
continue
confs_y = [confidence(d[n])[2] for n in X]
poly = [conf2poly(X, list(numpy.array(mean_y)+numpy.array(confs_y)), list(numpy.array(mean_y)-numpy.array(confs_y)), color=colors[j])]
patch_collection = PatchCollection(poly, match_original=True)
patch_collection.set_alpha(0.3)
patch_collection.set_linestyle('dashed')
fig.ax.add_collection(patch_collection)
fig.ax.plot(X, mean_y, label='$%d$' % nhdp_ht, color=colors[j])
fig.ax.set_xticks(X)
fig.ax.set_xticklabels(['$%s$' % i for i in X])
fig.ax.set_ylim(0,1)
fig.legend_title = legend_title
return fig
开发者ID:Dekue,项目名称:des-routing-algorithms,代码行数:25,代码来源:helpers.py
示例11: draw
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()
开发者ID:kareem94,项目名称:periodic-table-plotter,代码行数:33,代码来源:plotter.py
示例12: plotGrid
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()
开发者ID:jkulesza,项目名称:pydymax,代码行数:33,代码来源:examples.py
示例13: plotLandmasses
def plotLandmasses(verbose=True, save=False, show=True, dpi=300, resolution='c'):
'''Draw Landmasses Only, no Background'''
lonlat_islands, dymax_islands = getIslands(resolution)
patches = []
for island in dymax_islands:
#if np.all(island==islands[4]): print (island)
try: polygon = Polygon(np.array(island),closed=True, fill=True)
except: continue
#plt.plot(island[:,0],island[:,1])
patches.append(polygon)
plt.figure(figsize=(20,12),frameon=False)
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_landmasses.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
if show:
plt.tight_layout()
plt.show()
else: plt.close()
开发者ID:jkulesza,项目名称:pydymax,代码行数:31,代码来源:examples.py
示例14: draw
def draw(options):
files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]
degrees = list()
diameters = list()
velocities = list()
for f in files:
fin = open(options['outdir']+'/'+f, 'r')
ts = -1
for line in fin:
if line.startswith('#'):
continue
time, degree, diameter, velocity = [t.strip() for t in line.split(',')]
time = int(time)
assert(ts == time-1)
ts = time
try:
degrees[time].append(float(degree))
diameters[time].append(int(diameter))
velocities[time].append(float(velocity))
except IndexError:
degrees.append([float(degree)])
diameters.append([int(diameter)])
velocities.append([float(velocity)])
polies = list()
times = range(len(degrees))
times2 = times + times[::-1]
degrees_conf_upper = [confidence(d)[0] for d in degrees]
degrees_conf_lower = [confidence(d)[1] for d in degrees]
polies.append(conf2poly(times, degrees_conf_upper, degrees_conf_lower, color='blue'))
diameters_conf_upper = [confidence(d)[0] for d in diameters]
diameters_conf_lower = [confidence(d)[1] for d in diameters]
polies.append(conf2poly(times, diameters_conf_upper, diameters_conf_lower, color='blue'))
velocities_conf_upper = [confidence(d)[0] for d in velocities]
velocities_conf_lower = [confidence(d)[1] for d in velocities]
polies.append(conf2poly(times, velocities_conf_upper, velocities_conf_lower, color='green'))
velocities = [scipy.mean(d) for d in velocities]
diameters = [scipy.mean(d) for d in diameters]
degrees = [scipy.mean(d) for d in degrees]
fig = MyFig(options, figsize=(10, 8), xlabel='Time [s]', ylabel='Metric', grid=False, legend=True, aspect='auto', legend_pos='upper right')
patch_collection = PatchCollection(polies, match_original=True)
patch_collection.set_alpha(0.3)
patch_collection.set_linestyle('dashed')
fig.ax.add_collection(patch_collection)
fig.ax.plot(times, degrees, label='Mean degree', color='blue')
fig.ax.plot(times, diameters, label='Diameter', color='red')
fig.ax.plot(times, velocities, label='Mean velocity $[m/s]$', color='green')
fig.ax.set_xlim(0, options['duration'])
y_max = max(max(degrees), max(diameters), max(velocities))
fig.ax.set_ylim(0, y_max+10)
fig.save('metrics', fileformat='pdf')
开发者ID:Dekue,项目名称:des-routing-algorithms,代码行数:60,代码来源:random_waypoint.py
示例15: __init__
class Visualize:
def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]):
self.e = e.copy()
self.p = [Polygon(v[ti]) for ti in t]
self.p = PatchCollection(self.p, edgecolors='none')
self.l = LineCollection(v[e[:,:2]])
win = win or fig.canvas.manager.window
if fig is None: fig = gcf()
fig.clf()
ax = fig.add_axes([0.02,0.02,.98,.98])
ax.axis('scaled')
ax.axis(axesLimit)
ax.set_autoscale_on(False)
self.axis, self.fig, self.win = ax, fig, win
ax.add_collection(self.p)
ax.add_collection(self.l)
# ax.add_collection(self.l1)
# ax.add_collection(self.l2)
def update(self, title, phi):
norm = Normalize(phi.min(), phi.max())
self.p.set_norm(norm)
self.l.set_norm(norm)
self.p.set_array(phi)
self.l.set_array(phi[self.e[:,2:]].mean(1))
if not self.__dict__.has_key('colorbar'):
self.colorbar = self.fig.colorbar(self.p)
self.win.set_title(title)
#self.fig.canvas.set_window_title(title)
self.fig.canvas.draw()
开发者ID:gomezstevena,项目名称:x-wind,代码行数:32,代码来源:meshVisualize.py
示例16: _setup
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()
开发者ID:lhelwerd,项目名称:mobile-radio-tomography,代码行数:32,代码来源:Plot.py
示例17: plot_single_circle_grid
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")])
开发者ID:skriegman,项目名称:ppsn_2016,代码行数:32,代码来源:heatmaps.py
示例18: show_uboxes_corners
def show_uboxes_corners( corners, width, S=None, col='b', ecol='k' ):
"""
This version takes the corners and width arrays as arguments
instead.
"""
if corners.ndim != 2:
raise Exception("show_uboxes_corners: dimension must be 2")
if S is None:
S = range( len(corners) )
patches = []
for i in S:
art = mpatches.Rectangle( corners[i], width[0], width[1] )
patches.append(art)
fig = plt.figure()
ax = fig.gca()
ax.hold(True)
collection = PatchCollection(patches)
collection.set_facecolor(col)
collection.set_edgecolor(ecol)
ax.add_collection(collection,autolim=True)
ax.autoscale_view()
plt.show()
return fig
开发者ID:caosuomo,项目名称:rads,代码行数:26,代码来源:gfx.py
示例19: plotshapefile
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()
开发者ID:huhugravity,项目名称:mypythoncode,代码行数:29,代码来源:plot_shapefile.py
示例20: circles
def circles(x, y, s, c='b', ax=None, vmin=None, vmax=None, **kwargs):
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
import pylab as plt
if ax is None:
ax = plt.gca()
if isinstance(c,basestring):
color = c # ie. use colors.colorConverter.to_rgba_array(c)
else:
color = None # use cmap, norm after collection is created
kwargs.update(color=color)
if np.isscalar(x):
patches = [Circle((x, y), s),]
elif np.isscalar(s):
patches = [Circle((x_,y_), s) for x_,y_ in zip(x,y)]
else:
patches = [Circle((x_,y_), s_) for x_,y_,s_ in zip(x,y,s)]
collection = PatchCollection(patches, **kwargs)
if color is None:
collection.set_array(np.asarray(c))
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
ax.add_collection(collection)
ax.autoscale_view()
return collection
开发者ID:gajjarv,项目名称:serendip6,代码行数:28,代码来源:analyzeFits_v4.py
注:本文中的matplotlib.collections.PatchCollection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论