def __call__(self, plot):
from matplotlib.patches import Circle
if iterable(self.radius):
self.radius = plot.data.ds.quan(self.radius[0], self.radius[1])
self.radius = np.float64(self.radius.in_units(plot.xlim[0].units))
# This assures the radius has the appropriate size in
# the different coordinate systems, since one cannot simply
# apply a different transform for a length in the same way
# you can for a coordinate.
if self.coord_system == 'data' or self.coord_system == 'plot':
self.radius = self.radius * self.pixel_scale(plot)[0]
else:
self.radius /= (plot.xlim[1]-plot.xlim[0]).v
x,y = self.sanitize_coord_system(plot, self.center,
coord_system=self.coord_system)
cir = Circle((x, y), self.radius, transform=self.transform,
**self.circle_args)
xx0, xx1 = plot._axes.get_xlim()
yy0, yy1 = plot._axes.get_ylim()
plot._axes.add_patch(cir)
if self.text is not None:
label = plot._axes.text(x, y, self.text, transform=self.transform,
**self.text_args)
self._set_font_properties(plot, [label], **self.text_args)
plot._axes.set_xlim(xx0,xx1)
plot._axes.set_ylim(yy0,yy1)
python类Circle()的实例源码
def test_annotation2pltpatch():
assert list(ni.annotation2pltpatch(np.NaN)) == []
assert list(ni.annotation2pltpatch(())) == []
anno = ('point', ((1, 1), (1, 2)))
pltpatches = list(ni.annotation2pltpatch(anno))
assert len(pltpatches) == 2
assert isinstance(pltpatches[0], plp.CirclePolygon)
assert isinstance(pltpatches[1], plp.CirclePolygon)
anno = ('circle', ((2, 2, 2),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Circle)
anno = ('rect', ((1, 2, 2, 3),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Rectangle)
anno = ('polyline', (((1, 2), (3, 2), (3, 4), (1, 4), (1, 2)),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Polygon)
anno = ('polyline', (((0, 0), (2, 2), (2, 4)),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Polygon)
with pytest.raises(ValueError) as ex:
anno = ('invalid', ((1,),))
list(ni.annotation2pltpatch(anno))
assert str(ex.value).startswith('Invalid kind of annotation')
def annotation2pltpatch(annotation, **kwargs):
"""
Convert geometric annotation to matplotlib geometric objects (=patches)
For details regarding matplotlib patches see:
http://matplotlib.org/api/patches_api.html
For annotation formats see:
imageutil.annotation2coords
:param annotation annotation: Annotation of an image region such as
point, circle, rect or polyline
:return: matplotlib.patches
:rtype: generator over matplotlib patches
"""
if not annotation or isnan(annotation):
return
kind, geometries = annotation
for geo in geometries:
if kind == 'point':
pltpatch = plp.CirclePolygon((geo[0], geo[1]), 1, **kwargs)
elif kind == 'circle':
pltpatch = plp.Circle((geo[0], geo[1]), geo[2], **kwargs)
elif kind == 'rect':
x, y, w, h = geo
pltpatch = plp.Rectangle((x, y), w, h, **kwargs)
elif kind == 'polyline':
pltpatch = plp.Polygon(geo, closed=False, **kwargs)
else:
raise ValueError('Invalid kind of annotation: ' + kind)
yield pltpatch
def to_mpl_patch(self):
"""
This function ...
:return:
"""
return mpl_Circle((self.center.x, self.center.y), self.radius, edgecolor='green', facecolor='none', lw=3, alpha=0.7)
# -----------------------------------------------------------------
def to_mpl_patch(self):
"""
This function ...
:return:
"""
return mpl_Circle((self.center.x, self.center.y), self.radius, edgecolor='green', facecolor='none', lw=3, alpha=0.7)
# -----------------------------------------------------------------
def redraw_overplot_on_image(self, *args):
if self.star_center_patch is not None:
self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch)
if self.star_aperture_patch is not None:
self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch)
if self.sky_aperture_patch is not None:
self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch)
self.star_center_patch = Circle([self.xcentroid, self.ycentroid], 0.125, color=self.aprad_color)
self.ztv_frame.primary_image_panel.axes.add_patch(self.star_center_patch)
self.star_aperture_patch = Circle([self.xcentroid, self.ycentroid], self.aprad, color=self.aprad_color, alpha=self.alpha)
self.ztv_frame.primary_image_panel.axes.add_patch(self.star_aperture_patch)
self.sky_aperture_patch = Wedge([self.xcentroid, self.ycentroid], self.skyradout, 0., 360.,
width=self.skyradout - self.skyradin, color=self.skyrad_color, alpha=self.alpha)
self.ztv_frame.primary_image_panel.axes.add_patch(self.sky_aperture_patch)
self.ztv_frame.primary_image_panel.figure.canvas.draw()
self.hideshow_button.SetLabel(u"Hide")
def _clipcircle(self,ax,coll):
c = Circle((0.5*(self.xmax+self.xmin),0.5*(self.ymax+self.ymin)),
radius=0.5*(self.xmax-self.xmin),fc='none')
if c not in ax.patches:
p = ax.add_patch(c)
p.set_clip_on(False)
try:
coll.set_clip_path(c)
except:
for item in coll:
item.set_clip_path(c)
return coll,c
def _clipcircle(self,ax,coll):
c = Circle((0.5*(self.xmax+self.xmin),0.5*(self.ymax+self.ymin)),
radius=0.5*(self.xmax-self.xmin),fc='none')
if c not in ax.patches:
p = ax.add_patch(c)
p.set_clip_on(False)
try:
coll.set_clip_path(c)
except:
for item in coll:
item.set_clip_path(c)
return coll,c
def make_legend_circles_for(sizes, scale=1.0, **kw):
return [Circle((0,0), radius=(s/scale)**0.5, **kw) for s in sizes]
def plot_circle_in_micrograph(micrograph_2d, coordinate, particle_size, filename, color = 'white'):
"""plot the particle circle in micrograph image
Based on the coordinate of particle, plot circles of the particles in the micrograph.
And save the ploted image in filename.
Args:
micrograph_2d: numpy.array,it is a 2D numpy array.
coordinate: list, it is a 2D list, the shape is (num_particle, 2).
particle_size: int, the value of the particle size
filename: the filename of the image to be save.
color: define the color of the circle
Raises:
pass
"""
micrograph_2d = micrograph_2d.reshape(micrograph_2d.shape[0], micrograph_2d.shape[1])
fig = plt.figure()
ax = fig.add_subplot(111)
plt.axis('off')
plt.gray()
plt.imshow(micrograph_2d)
radius = particle_size/2
i = 0
while True:
if i >= len(coordinate):
break
coordinate_x = coordinate[i][0]
coordinate_y = coordinate[i][1]
cir1 = Circle(xy = (coordinate_x, coordinate_y), radius = radius, alpha = 0.5, color = color, fill = False)
ax.add_patch(cir1)
# extract the particles
i = i + 1
plt.savefig(filename)
def plotDetector(self):
""" plot a detector (circle) to plt figure """
ax = plt.gca()
ax.add_patch(patches.Circle((self.center[0],
self.center[1]),
self.radius,
fill = False))
def plotDetector(self):
""" plot a detector (circle) to plt figure """
ax = plt.gca()
ax.add_patch(patches.Circle((self.center[0],
self.center[1]),
self.radius,
fill = False))
def _plot_sensors(pos_x, pos_y, sensors, ax):
"""Aux function"""
from matplotlib.patches import Circle
if sensors is True:
for x, y in zip(pos_x, pos_y):
ax.add_artist(Circle(xy=(x, y), radius=0.003, color='k'))
else:
ax.plot(pos_x, pos_y, sensors)
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
# https://matplotlib.org/examples/color/colormaps_reference.html
patches = []
for pos in var:
if shape == 'c':
patches.append(mpatches.Circle(pos, r))
elif shape == 'r':
patches.append(mpatches.RegularPolygon(pos, 4, r))
elif shape == 's':
patches.append(mpatches.RegularPolygon(pos, 6, r))
colors = np.linspace(start_color, .9, len(patches))
collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
collection.set_array(np.array(colors))
collection.set_clim(0, 1)
return collection
def plot_3d_ball_trajectory(var, filename, r=0.05):
var = np.asarray(var)
# Normalize directions
var -= var.min(axis=0)
var /= var.max(axis=0)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for x, y, z in var:
p = mpatches.Circle((x, y), r, ec="none")
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")
p = mpatches.Circle((x, z), r, ec="none")
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="y")
p = mpatches.Circle((y, z), r, ec="none")
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
# ax.scatter(x, y, z, s=100)
# ax.plot(var[:, 0], var[:, 1], zs=var[:, 2])
ax.view_init(azim=45, elev=30)
ax.set_xlim3d(-0.1, 1.1)
ax.set_ylim3d(-0.1, 1.1)
ax.set_zlim3d(-0.1, 1.1)
plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
plt.close(fig)
# plt.show()
def _print_junction(self):
bw = self.game_params['board_width']
lw = self.game_params['lane_width']
# road marks
plt.vlines(lw, -bw, -lw)
plt.vlines(-lw, -bw, -lw)
plt.vlines(-lw, lw, bw)
plt.vlines(lw, lw, bw)
plt.hlines(-lw, -bw, -lw)
plt.hlines(-lw, lw, bw)
plt.hlines(lw, -bw, -lw)
plt.hlines(lw, lw, bw)
# lane marks
plt.vlines(0, -bw, -lw, linestyles='dashed')
plt.vlines(0, lw, bw, linestyles='dashed')
plt.hlines(0, -bw, -lw, linestyles='dashed')
plt.hlines(0, lw, bw, linestyles='dashed')
# stopping lines
plt.hlines(-lw, 0, lw, linestyles='solid')
plt.hlines(-lw-0.01, 0, lw, linestyles='solid')
plt.hlines(lw, -lw, 0, linestyles='solid')
plt.hlines(lw+0.01, -lw, 0, linestyles='solid')
plt.vlines(-lw, -lw, 0, linestyles='solid')
plt.vlines(-lw-0.01, -lw, 0, linestyles='solid')
plt.vlines(lw, 0, lw, linestyles='solid')
plt.vlines(lw+0.01, 0, lw, linestyles='solid')
# print rails
# self.ax.add_patch(Circle(xy=(lw,-lw), radius=lw/2, edgecolor='k', facecolor='none'))
# self.ax.add_patch(Circle(xy=(-lw,-lw), radius=3*lw/2, edgecolor='k', facecolor='none'))
def plot_encoding(model, sess, title=None, name="encoding",
datasets=("test","validation"), range_=(-4.,4.),
save=True, outdir="./plots", **kwargs):
"""
Plotting utility to encode dataset images in (low dimensional!) latent space
"""
# TODO: check for 2d
title = (title if title else name)
for dataset_name in datasets:
dataset = getattr(model.dataset, dataset_name)
feed_dict = {model.x_in_test: dataset.images}
encoding = sess.run(model.z_dist_info_, feed_dict=feed_dict)
centers = encoding[model.latent_dist.dist_info_keys[0]]
ys, xs = centers.T
plt.figure()
plt.title("round {}: {} in latent space".format(model.counter,
dataset_name))
kwargs = {'alpha': 0.8}
classes = set(dataset.labels)
if classes:
colormap = plt.cm.rainbow(np.linspace(0, 1, len(classes)))
kwargs['c'] = [colormap[i] for i in dataset.labels]
# make room for legend
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
handles = [mpatches.Circle((0,0), label=class_, color=colormap[i])
for i, class_ in enumerate(classes)]
ax.legend(handles=handles, shadow=True, bbox_to_anchor=(1.05, 0.45),
fancybox=True, loc='center left')
plt.scatter(xs, ys, **kwargs)
# map range_ to standard deviations of the target distribution
stddev = model.target_dist.stddev
adjusted_range = (stddev*range_[0], stddev*range_[1])
if range_:
plt.xlim(adjusted_range)
plt.ylim(adjusted_range)
if save:
title = "{}_encoding_{}_round_{}.png".format(
model.datetime, dataset_name, model.counter)
plt.savefig(os.path.join(outdir, title), bbox_inches="tight")
plt.close()
def compute_venn3_areas(diagram_areas, normalize_to=1.0, _minimal_area=1e-6):
'''
The list of venn areas is given as 7 values, corresponding to venn diagram areas in the following order:
(Abc, aBc, ABc, abC, AbC, aBC, ABC)
(i.e. last element corresponds to the size of intersection A&B&C).
The return value is a list of areas (A_a, A_b, A_c, A_ab, A_bc, A_ac, A_abc),
such that the total area of all circles is normalized to normalize_to.
If the area of any circle is smaller than _minimal_area, makes it equal to _minimal_area.
Assumes all input values are nonnegative (to be more precise, all areas are passed through and abs() function)
>>> compute_venn3_areas((1, 1, 0, 1, 0, 0, 0))
(0.33..., 0.33..., 0.33..., 0.0, 0.0, 0.0, 0.0)
>>> compute_venn3_areas((0, 0, 0, 0, 0, 0, 0))
(1e-06, 1e-06, 1e-06, 0.0, 0.0, 0.0, 0.0)
>>> compute_venn3_areas((1, 1, 1, 1, 1, 1, 1), normalize_to=7)
(4.0, 4.0, 4.0, 2.0, 2.0, 2.0, 1.0)
>>> compute_venn3_areas((1, 2, 3, 4, 5, 6, 7), normalize_to=56/2)
(16.0, 18.0, 22.0, 10.0, 13.0, 12.0, 7.0)
'''
# Normalize input values to sum to 1
areas = np.array(np.abs(diagram_areas), float)
total_area = np.sum(areas)
if np.abs(total_area) < _minimal_area:
warnings.warn("All circles have zero area")
return (1e-06, 1e-06, 1e-06, 0.0, 0.0, 0.0, 0.0)
else:
areas = areas / total_area * normalize_to
A_a = areas[0] + areas[2] + areas[4] + areas[6]
if A_a < _minimal_area:
warnings.warn("Circle A has zero area")
A_a = _minimal_area
A_b = areas[1] + areas[2] + areas[5] + areas[6]
if A_b < _minimal_area:
warnings.warn("Circle B has zero area")
A_b = _minimal_area
A_c = areas[3] + areas[4] + areas[5] + areas[6]
if A_c < _minimal_area:
warnings.warn("Circle C has zero area")
A_c = _minimal_area
# Areas of the three intersections (ab, ac, bc)
A_ab, A_ac, A_bc = areas[2] + areas[6], areas[4] + areas[6], areas[5] + areas[6]
return (A_a, A_b, A_c, A_ab, A_bc, A_ac, areas[6])
def plotHeadOutline(ax=None, radius=1.2):
result = {}
# if new axis not given, create one
if ax is None:
fig = plt.figure(figsize=(11,8))
result['fig'] = fig
ax = fig.add_subplot(1,1,1, aspect='equal')
result['ax'] = ax
extent = (-0.16-radius,0.16+radius,-0.01-radius,0.20+radius)
result['extent'] = extent
ax.set_aspect('equal')
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])
leftEar = pltPatches.Ellipse((-0.075-radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False)
ax.add_patch(leftEar)
rightEar = pltPatches.Ellipse((0.075+radius,0.0), width=0.15, height=0.4, angle=0.0, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False)
ax.add_patch(rightEar)
result['leftEar'] = leftEar
result['rightEar'] = rightEar
noseLength = 0.18
noseWidth = 0.12
noseIntersect = 2.0*radius-np.sqrt(noseWidth**2+radius**2)
leftNose, = ax.plot((0.0,-noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10)
rightNose, = ax.plot((0.0,noseWidth), (radius+noseLength,noseIntersect), color='dimgrey', linewidth=3, zorder=10)
leftNose.set_solid_capstyle('round')
rightNose.set_solid_capstyle('round')
result['leftNose'] = leftNose
result['rightNose'] = rightNose
head = pltPatches.Circle((0.0,0.0), radius, edgecolor='dimgrey', facecolor='white', linewidth=3, zorder=10, fill=False)
result['head'] = head
ax.add_patch(head)
ax.set_xticks([])
ax.set_yticks([])
return result
def plotHead(chanNames=('F3','F4','C3','C4','P3','P4','O1','O2'),
radius=0.01, fillColor='black', lineColor='black',
drawLabels=True, clip=True, fontSize=12, ax=None, **kwargs):
# plot head outline and save result dict
result = plotHeadOutline(ax)
ax = result['ax']
# get chanNames that we have a location for
chanNames = [chanName for chanName in chanNames if chanName.lower() in chanLocs3d.keys()]
chanNamesLower = [chanName.lower() for chanName in chanNames] # lower case
# if no valid chanNames then just draw the outline
if len(chanNames) == 0:
return result
# get 3d cartesian coordinates for each channel
xyz = np.asarray([chanLocs3d[chanName] for chanName in chanNamesLower])
# make sure coordinates have unit magnitude
xyz = xyz / np.sqrt(np.sum(xyz**2, axis=1))[:,None]
# rotate by pi/2 around z axis
cos90 = np.cos(np.pi/2.0)
rot = np.asarray(((cos90,-1.0,0.0),(1.0,cos90,0.0),(0.0,0.0,1.0))).T
xyz = xyz.dot(rot)
# stereographic projection
x = xyz[:,0]
y = xyz[:,1]
z = xyz[:,2]
xy = np.vstack((x/(1.0+z), y/(1.0+z))).T
# list of circles and chan labels to store in result
circles = []
chanLabels = []
# for each channel
for chanName, coord in zip(chanNames, xy):
x, y = coord
c = pltPatches.Circle((x,y), radius, edgecolor=lineColor,
facecolor=fillColor, linewidth=1, fill=True, zorder=100)
ax.add_patch(c)
circles.append(c)
# draw channel labels
if drawLabels:
if fontSize is not None:
txt = ax.text(x,y+0.081, chanName, size=fontSize,
horizontalalignment='center', verticalalignment='center', zorder=100)
chanLabels.append(txt)
# save labels and circles in result
result['chanLabels'] = chanLabels
result['circles'] = circles
return result