本文整理汇总了Python中matplotlib.path.Path类的典型用法代码示例。如果您正苦于以下问题:Python Path类的具体用法?Python Path怎么用?Python Path使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Path类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: selectArea
def selectArea(self, ptlist, latlon=False, reduced=None):
"""Select an area of the grid.
Parameters
----------
ptlist : list
latlon : bool
reduced : int
The amount by which the index array should be short (i.e., 1 for
basic difference, 2 for center difference).
"""
ptlist = np.asarray(ptlist)
if latlon:
ptlist[:,0], ptlist[:,1] = self.basemap(ptlist[:,0], ptlist[:,1])
# create the polygon
path = Path(ptlist)
if reduced is not None:
X, Y = np.meshgrid(self.x[:-reduced], self.y[:-reduced])
areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
areaind = areaind.reshape((self.shape[0]-reduced,
self.shape[1]-reduced))
else:
X, Y = np.meshgrid(self.x, self.y)
areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
areaind = areaind.reshape(self.shape)
# return array indices
return areaind
开发者ID:skachuck,项目名称:giapy,代码行数:28,代码来源:map_tools.py
示例2: reverse_geocode
def reverse_geocode(tweet):
# print index
# latlong = json.load(tweets)[index]['coordinates']
latlong = tweet["coordinates"]
if latlong == [0.0, 0.0]:
return False
# latlong.reverse()
with open('world-countries.json.txt', 'r') as countries_json:
found_country = None
countries = json.load(countries_json)['features']
for country in countries:
country_name = country['properties']['name']
if country['geometry']['type'] == 'Polygon':
country_vertices = country['geometry']['coordinates'][0]
country_path = Path(country_vertices)
if country_path.contains_point(latlong):
found_country = country_name
break
if country['geometry']['type'] == 'MultiPolygon':
country_polygons = country['geometry']['coordinates']
for polygon in country_polygons:
country_vertices = polygon[0]
country_path = Path(country_vertices)
if country_path.contains_point(latlong):
found_country = country_name
break
if not found_country:
found_country = False
return found_country
# with open('Ferguson_tweets.txt', 'r') as tweets:
# print reverse_geocode(tweets, 0)
开发者ID:seashark97,项目名称:Sentiment-heat-map-generator,代码行数:31,代码来源:reverse_geocoder.py
示例3: processPolygon
def processPolygon(polygon, rows, columns, mode):
"""
Finds the points within a particular polygon
"""
length = len(polygon)
polygon.append((0.0, 0.0))
codes = [Path.MOVETO]
for index in range(length - 1):
codes.append(Path.LINETO)
codes.append(Path.CLOSEPOLY)
path = Path(polygon, codes)
points = []
if mode == 'V':
for index in range(rows):
row = [(x, index) for x in range(columns)]
check = path.contains_points(row)
temp_points = ([row[i] for i, j in enumerate(check) if j == True and not contains(row[i], polygon)])
if (len(temp_points) > 0):
points.append(temp_points)
else:
for index in range(columns):
col = [(index, x) for x in range(rows)]
check = path.contains_points(col)
temp_points = ([col[i] for i, j in enumerate(check) if j == True and not contains(col[i], polygon)])
if (len(temp_points) > 0):
points.append(temp_points)
return points
开发者ID:harikv,项目名称:CS4243Project,代码行数:27,代码来源:buildTextures.py
示例4: pca_var
def pca_var(sub_dims):
data = np.array([df[d] for d in sub_dims]).T
try: pca = PCA(data, standardize=True)
except: return 0,1,0,1,None,None,None,sub_dims
classed_points = zip(classes, pca.Y)
pos = [(it[0], it[1]) for c, it in classed_points if c]
neg = [(it[0], it[1]) for c, it in classed_points if not c]
P_hull = [pos[i] for i in ConvexHull(pos).vertices]; P_hull.append(P_hull[0])
N_hull = [neg[i] for i in ConvexHull(neg).vertices]; N_hull.append(N_hull[0])
P_hull = np.array(P_hull)
N_hull = np.array(N_hull)
P_path = Path(P_hull)
N_path = Path(N_hull)
N_sep = 0
for it in neg:
if not P_path.contains_point(it):
N_sep += 1
P_sep = 0
for it in pos:
if not N_path.contains_point(it):
P_sep += 1
return N_sep, float(len(neg)), P_sep, float(len(pos)), P_hull, N_hull, pca, sub_dims
开发者ID:qfeys,项目名称:ThrottleControlledAvionics,代码行数:26,代码来源:REN-optimization.py
示例5: transform_path_non_affine
def transform_path_non_affine(self, path):
# Adaptive interpolation:
# we keep adding control points, till all control points
# have an error of less than 0.01 (about 1%)
# or if the number of control points is > 80.
ra0 = self.ra0
path = path.cleaned(curves=False)
v = path.vertices
diff = v[:, 0] - v[0, 0]
v00 = v[0][0] - ra0
while v00 > 180: v00 -= 360
while v00 < -180: v00 += 360
v00 += ra0
v[:, 0] = v00 + diff
nonstop = path.codes > 0
path = Path(v[nonstop], path.codes[nonstop])
isteps = path._interpolation_steps * 2
while True:
ipath = path.interpolated(isteps)
tiv = self.transform(ipath.vertices)
itv = Path(self.transform(path.vertices)).interpolated(isteps).vertices
if np.mean(np.abs(tiv - itv)) < 0.01:
break
if isteps > 20:
break
isteps = isteps * 2
return Path(tiv, ipath.codes)
开发者ID:rainwoodman,项目名称:skymapper,代码行数:27,代码来源:aea_projection.py
示例6: contained_in
def contained_in(lat, lng, bound_coords):
"""
Returns true if (lat, lng) is contained within the polygon formed by the
points in bound_coords.
"""
bound_path = Path(np.array(bound_coords))
return bound_path.contains_point((lat, lng))
开发者ID:ncanac,项目名称:datasci_course_materials,代码行数:7,代码来源:happiest_state.py
示例7: test_path_no_doubled_point_in_to_polygon
def test_path_no_doubled_point_in_to_polygon():
hand = np.array(
[[1.64516129, 1.16145833],
[1.64516129, 1.59375],
[1.35080645, 1.921875],
[1.375, 2.18229167],
[1.68548387, 1.9375],
[1.60887097, 2.55208333],
[1.68548387, 2.69791667],
[1.76209677, 2.56770833],
[1.83064516, 1.97395833],
[1.89516129, 2.75],
[1.9516129, 2.84895833],
[2.01209677, 2.76041667],
[1.99193548, 1.99479167],
[2.11290323, 2.63020833],
[2.2016129, 2.734375],
[2.25403226, 2.60416667],
[2.14919355, 1.953125],
[2.30645161, 2.36979167],
[2.39112903, 2.36979167],
[2.41532258, 2.1875],
[2.1733871, 1.703125],
[2.07782258, 1.16666667]])
(r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
assert np.all(poly_clipped[-2] != poly_clipped[-1])
assert np.all(poly_clipped[-1] == poly_clipped[0])
开发者ID:DanHickstein,项目名称:matplotlib,代码行数:33,代码来源:test_path.py
示例8: _gating
def _gating(self,DF_array_data,x_ax,y_ax,coords):
#np.ones(DF_array_data.shape[0],dtype=bool)
gate=Path(coords,closed=True)
projection=np.array(DF_array_data[[x_ax,y_ax]])
index=gate.contains_points(projection)
return index
开发者ID:davidpng,项目名称:Myeloid_Machine_Learning,代码行数:7,代码来源:HEADER_Import_FCS.py
示例9: paths_in_shape
def paths_in_shape(paths):
shape = shape_(shape_path)
minx, miny, maxx, maxy = shape.bounds
#print minx; print miny; print maxx; print maxy
#bounding_box = geometry.box(minx, miny, maxx, maxy)
#generate random points within bounding box!
sf = shapefile.Reader(shape_path)
shape = sf.shapes()[0]
#find polygon nodes lat lons
verticies = shape.points
#convert to a matplotlib path class!
polygon = Path(verticies)
points_in_shape = polygon.contains_points(paths)
points_in_shape = paths[points_in_shape == True]
return points_in_shape
开发者ID:iceseismic,项目名称:SeisSuite,代码行数:25,代码来源:pointshape.py
示例10: __init__
def __init__(self, shape, scale=1):
"""
Initalize a Warper with a reference shape with coordinates in the
numpy array 'shape'
"""
xy = shape.copy() * scale
self.scale = scale
xy = self.shape_to_xy(xy)
xy = xy - np.min(xy,axis=0)
dt = scipy.spatial.Delaunay(xy)
# Define a grid
cols = int(np.ceil(np.max(xy[:,0])))
rows = int(np.ceil(np.max(xy[:,1])))
xx, yy = np.meshgrid(range(cols),range(rows))
xy_grid = np.vstack((xx.flatten(),yy.flatten())).T
# Define a mask
mask = Path(xy).contains_points(xy_grid)
self.mask = mask.reshape(xx.shape)
xy_grid = xy_grid[mask==True,:] # Remove pts not inside mask
# Calculate barycentric coordinates for all points inside mask
simplex_ids = dt.find_simplex(xy_grid)
bary_coords = points_to_bary(dt,simplex_ids,xy_grid)
self.tri = dt.simplices
self.warp_template = np.hstack((simplex_ids[:,np.newaxis],bary_coords))
开发者ID:schackv,项目名称:shapewarp,代码行数:31,代码来源:warp.py
示例11: _endGate
def _endGate(self, event):
#draw gate rectangle
start_x = self.start_x if self.start_x < event.xdata else event.xdata
start_y = self.start_y if self.start_y < event.ydata else event.ydata
width = np.absolute(event.xdata-self.start_x)
height = np.absolute(event.ydata-self.start_y)
rect = Rectangle((start_x, start_y), width, height,
fill=False, ec='black', alpha=1, lw=2)
self.ax.add_patch(rect)
self.canvas.draw()
#disable mouse events
self.canvas.mpl_disconnect(self.buttonPress)
self.canvas.mpl_disconnect(self.buttonRelease)
self.canvas.get_tk_widget().config(cursor='arrow')
#save cell gate
gate = Path([[start_x, start_y],
[start_x + width, start_y],
[start_x + width, start_y + height],
[start_x, start_y + height],
[start_x, start_y]])
gated_cells = self.scdata.tsne.index[gate.contains_points(self.scdata.tsne)]
self.gates[self.gateName.get()] = gated_cells
#replot tSNE w gate colored
self.fig.clf()
plt.scatter(self.scdata.tsne['x'], self.scdata.tsne['y'], s=10, edgecolors='none', color='lightgrey')
plt.scatter(self.scdata.tsne.ix[gated_cells, 'x'], self.scdata.tsne.ix[gated_cells, 'y'], s=10, edgecolors='none')
self.canvas.draw()
self.setGateButton.config(state='disabled')
self.visMenu.entryconfig(6, state='disabled')
开发者ID:Colelyman,项目名称:wishbone,代码行数:33,代码来源:wishbone_gui.py
示例12: distribute_pixels
def distribute_pixels(self, edges, length, width):
corners = self.get_corners()
reg_path = Path(corners)
# Get region boundaries.
bounds = reg_path.get_extents().get_points()
[[x_min_bound, y_min_bound], [x_max_bound, y_max_bound]] = bounds
# For cases when the boundary pixels are not integers:
x_min_bound = floor(x_min_bound)
y_min_bound = floor(y_min_bound)
x_max_bound = ceil(x_max_bound)
y_max_bound = ceil(y_max_bound)
pixels_in_bins = []
for x in range(max(0, x_min_bound), min(x_max_bound+1, width)):
for y in range(max(0, y_min_bound), min(y_max_bound+1, length)):
if reg_path.contains_point((x, y)):
x_nonrotated, y_nonrotated = rotate_point(self.x0, self.y0,
x - self.x0,
y - self.y0,
-self.angle)
dist_from_box_bottom = self.height/2. - \
(self.y0 - y_nonrotated)
for i, edge in enumerate(edges[1:]):
if edge > dist_from_box_bottom:
pixels_in_bins.append((y, x, i))
break
return pixels_in_bins
开发者ID:gogrean,项目名称:PyXel,代码行数:26,代码来源:box.py
示例13: test_point_in_path_nan
def test_point_in_path_nan():
box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
p = Path(box)
test = np.array([[np.nan, 0.5]])
contains = p.contains_points(test)
assert len(contains) == 1
assert not contains[0]
开发者ID:DanHickstein,项目名称:matplotlib,代码行数:7,代码来源:test_path.py
示例14: onselect
def onselect(self, verts):
path = Path(verts)
self.ind = np.nonzero([path.contains_point(xy) for xy in self.xys])[0]
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
开发者ID:fedhere,项目名称:detect120,代码行数:7,代码来源:lassoselect.py
示例15: get_mask_img
def get_mask_img(transform, target_bin, camera_model):
"""
:param point: point that is going to be transformed
:type point: PointStamped
:param transform: camera_frame -> bbox_frame
:type transform: Transform
"""
# check frame_id of a point and transform just in case
assert camera_model.tf_frame == transform.header.frame_id
assert target_bin.bbox.header.frame_id == transform.child_frame_id
transformed_list = [
do_transform_point(corner, transform)
for corner in target_bin.corners]
projected_points = project_points(transformed_list, camera_model)
# generate an polygon that covers the region
path = Path(projected_points)
x, y = np.meshgrid(
np.arange(camera_model.width),
np.arange(camera_model.height))
x, y = x.flatten(), y.flatten()
points = np.vstack((x, y)).T
mask_img = path.contains_points(
points).reshape(
camera_model.height, camera_model.width
).astype('bool')
return mask_img
开发者ID:yuyu2172,项目名称:jsk_apc,代码行数:28,代码来源:rbo_preprocessing.py
示例16: estimate_mean_extinction
def estimate_mean_extinction(self, poly):
"""Estimate the mean extinction Av in within a footprint.
Parameters
----------
poly : ndarray
The RA,Dec polygon (a rectangle) defining the footprint.
"""
sigma_dust = self._f[0].data
ny, nx = sigma_dust.shape
# Make a coordinate grid out of RA, Dec across the dust map
y_image, x_image = np.mgrid[0:ny, 0:nx]
y = y_image.reshape(nx * ny)
x = x_image.reshape(nx * ny)
ra, dec = self._wcs.all_pix2world(x, y, 0)
points = np.vstack((ra, dec)).T
# Find all pixels in the footprint
path = Path(poly, closed=False)
in_poly = path.contains_points(points)
s = np.where(in_poly)[0]
dust_pixels = sigma_dust[y[s], x[s]]
mean = np.nanmean(dust_pixels)
# Estimate Av from the Lewis et al attenuation law
return 10. ** (-5.4) * mean
开发者ID:jonathansick,项目名称:androcmd,代码行数:27,代码来源:dust.py
示例17: make_venn3_region_patch
def make_venn3_region_patch(region):
'''
Given a venn3 region (as returned from compute_venn3_regions) produces a Patch object,
depicting the region as a curve.
>>> centers, radii = solve_venn3_circles((1, 1, 1, 1, 1, 1, 1))
>>> regions = compute_venn3_regions(centers, radii)
>>> patches = [make_venn3_region_patch(r) for r in regions]
'''
if region is None or len(region[0]) == 0:
return None
if region[0] == "CIRCLE":
return Circle(region[1][0], region[1][1])
pts, arcs, label_pos = region
path = [pts[0]]
for i in range(len(pts)):
j = (i + 1) % len(pts)
(center, radius, direction) = arcs[i]
fromangle = vector_angle_in_degrees(pts[i] - center)
toangle = vector_angle_in_degrees(pts[j] - center)
if direction:
vertices = Path.arc(fromangle, toangle).vertices
else:
vertices = Path.arc(toangle, fromangle).vertices
vertices = vertices[np.arange(len(vertices) - 1, -1, -1)]
vertices = vertices * radius + center
path = path + list(vertices[1:])
codes = [1] + [4] * (len(path) - 1)
return PathPatch(Path(path, codes))
开发者ID:perphyliu,项目名称:matplotlib-venn,代码行数:29,代码来源:_venn3.py
示例18: path_contains_points
def path_contains_points(verts, points):
p = Path(verts, closed=True)
result = num.zeros(points.shape[0], dtype=num.bool)
for i in range(result.size):
result[i] = p.contains_point(points[i, :])
return result
开发者ID:hvasbath,项目名称:pyrocko,代码行数:7,代码来源:orthodrome.py
示例19: _filter_block
def _filter_block(vertices, block_origin, block_shape):
"""
Keyword arguments:
vertices --
block_origin_list --
block_shape --
Return values
-- True/False vertices contain block
"""
# check arguments
# create path object
path = Path(vertices, closed=True)
# create path for the block
x0 = block_origin[0]
y0 = block_origin[1]
w = block_shape[0]
h = block_shape[1]
box_vertices = np.asarray([[x0, y0], [x0 + w, y0], [x0 + w, y0 + h], [x0, y0 + h]])
box = Path(box_vertices, closed=True)
# determine if points inside the specified path
# Note: there appears to be an error in contains_points(). For
# example, reversing the direction of the vertices requires raidus=-0.01
# to be specified. See the e-mails in the link below
# http://matplotlib.1069221.n5.nabble.com/How-to-properly-use-path-Path-contains-point-tc40718.html#none
return path.contains_path(box)
开发者ID:aluchies,项目名称:utils,代码行数:33,代码来源:array_tools.py
示例20: get_path
def get_path( img, verts ):
#verts=array( verts, int)
path1 = Path(verts)
print path1
dx,dy=img.shape
data = zeros( [dx,dy,2])
data[:,:,0]= range(dx)
for i in range(dy):
data[i,:,1] = i
#print data
data=data.reshape( [dx*dy,2])
#print data.shape
#print path1,data
index = path1.contains_points(data)
print index.shape, len(where(index)[0])
#print data[index, :2]
#plot(data[:,0],data[:,1], 'b.')
fig, ax = plt.subplots(nrows=1)
vmin=img.min();vmax=img.max()
ax.imshow( img,cmap=plt.get_cmap('winter'), vmin=vmin,vmax=vmax )
#ax.set_xlim(0,dx-1)
#ax.set_ylim(0,dy-1)
patch = patches.PathPatch(path1, facecolor='orange', lw=2)
gca().add_patch(patch)
plot(data[index,0], data[index,1], 'r.')
show()
开发者ID:yugangzhang,项目名称:notebook_XPCS,代码行数:27,代码来源:Mask_Maker.py
注:本文中的matplotlib.path.Path类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论