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")
python类Circle()的实例源码
def draw_nodes(self):
"""
Renders nodes to the figure.
"""
node_r = self.nodeprops['radius']
lw = self.nodeprops['linewidth']
for i, node in enumerate(self.nodes):
x = self.node_coords['x'][i]
y = self.node_coords['y'][i]
color = self.node_colors[i]
node_patch = patches.Circle((x, y), node_r,
lw=lw, color=color,
zorder=2)
self.ax.add_patch(node_patch)
if self.node_labels:
label_x = self.node_label_coords['x'][i]
label_y = self.node_label_coords['y'][i]
label_ha = self.node_label_aligns['has'][i]
label_va = self.node_label_aligns['vas'][i]
self.ax.text(s=node,
x=label_x, y=label_y,
ha=label_ha, va=label_va)
def drawCenterMarker(self):
"""Draws a yellow marker in center of the image, making it
easier to find image center when selecting center of boundary."""
centerImg=[self.img.shape[0]/2.,self.img.shape[1]/2.]
if len(self.centerMarker)>0:
self.clearCenterMarker()
else:
pt=ptc.Circle(centerImg,radius=3,fill=True,color='y')
self.centerMarker.append(self.ax.add_patch(pt))
self.fig.canvas.draw()
return self.centerMarker
def plot(self, ax):
"""Plot a two-dimensional environment.
Parameters
----------
ax : Axis
Matplotlib axis
"""
if self.n_task_dims != 2:
raise ValueError("Can only plot 2 dimensional environments")
ax.scatter(self.x0[0], self.x0[1], c="r", s=100)
ax.scatter(self.g[0], self.g[1], c="g", s=100)
if self.obstacles is not None:
from matplotlib.patches import Circle
for obstacle in self.obstacles:
ax.add_patch(Circle(obstacle, self.obstacle_dist, ec="none",
color="r"))
GraphicRecord.py 文件源码
项目:DnaFeaturesViewer
作者: Edinburgh-Genome-Foundry
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def initialize_ax(self, ax, draw_line, with_ruler):
if draw_line:
circle = mpatches.Circle(
(0, -self.radius), self.radius, facecolor='none',
edgecolor='k')
ax.add_patch(circle)
ax.axis("off")
if with_ruler: # only display the xaxis ticks
ax.set_frame_on(False)
ax.yaxis.set_visible(False)
ax.xaxis.tick_bottom()
else: # don't display anything
ax.axis("off")
ax.set_xlim(-self.radius, self.radius)
ax.set_aspect("equal")
def __update_artist(self):
# check if this is the first point of a branch
if self.artist is None:
self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False,
lw=2, color='red')
self.axes.add_artist(self.artist)
elif len(self.x) == 0:
self.artist.remove()
self.artist = None
elif len(self.x) == 1:
self.artist.remove()
self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False,
lw=2, color='red')
self.axes.add_artist(self.artist)
# change from circle to polygon if more than 1 points are available
elif len(self.x) == 2:
self.artist.remove()
branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r)
self.artist = Polygon(branch.outline, fill=False, color='red', lw=2)
self.axes.add_artist(self.artist)
else:
assert (len(self.x) > 2)
branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r)
self.artist.set_xy(branch.outline)
def make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False):
fig = ax.get_figure()
def axes2pt():
return np.diff(
ax.transData.transform([(0,0), (1,1)]), axis=0)[0] * (72./fig.dpi)
ellipses = []
if not dont_resize_actively:
def update_width_height(event):
dist = axes2pt()
for e, radius in ellipses: e.width, e.height = 2. * radius * dist
fig.canvas.mpl_connect('resize_event', update_width_height)
ax.callbacks.connect('xlim_changed', update_width_height)
ax.callbacks.connect('ylim_changed', update_width_height)
def legend_circle_handler(legend, orig_handle, xdescent, ydescent,
width, height, fontsize):
w, h = 2. * orig_handle.get_radius() * axes2pt()
e = Ellipse(xy=(0.5*width-0.5*xdescent, 0.5*height-0.5*ydescent),
width=w, height=w)
ellipses.append((e, orig_handle.get_radius()))
return e
return {Circle: HandlerPatch(patch_func=legend_circle_handler)}
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
c = orig_handle
x0, y0 = handlebox.xdescent, handlebox.ydescent
x1, y1 = handlebox.width, handlebox.height
x = (x0+x1)/2.
y = (y0+y1)/2.
r = min((x1-x0)/2., (y1-y0)/2.)
patch = mpatches.Circle((x, y), 2.*r, facecolor=c,
alpha=0.5, lw=0,
transform=handlebox.get_transform())
point = mpatches.Circle((x, y), r/2., facecolor=c,
alpha=1.0, lw=0,
transform=handlebox.get_transform())
handlebox.add_artist(patch)
handlebox.add_artist(point)
return patch,point
# Parse input
#Get number of euler rotations
def __init__(self, axes, sim, type_to_radius, type_to_color):
assert len(type_to_radius) == len(type_to_color)
particle_types_arr = sim.types
self._typeToRadius = type_to_radius
self._typeToColor = type_to_color
self._particleCircles = []
self._sim = sim
for particleType in particle_types_arr:
c = Circle((0, 0, 0), type_to_radius[particleType], )
c.set_color(self._typeToColor[particleType])
self._particleCircles.append(c)
axes.add_patch(c)
axes.set_xlim([0, sim.domain_size[0]])
axes.set_ylim([0, sim.domain_size[1]])
axes.set_aspect('equal')
def draw_rolled_sup(ax,node,factor = 1,**kwargs):
r = 0.1*factor
patch = mpatches.Circle((node.x, node.y),radius = r/2.,**kwargs)
ax.add_patch(patch)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = Circle(xy=center, radius=width / 4.0, alpha=0.4)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
def plot_labelprop_mpl(coords, communities, file_name=None, title=''):
u_community = np.unique(communities)
cmap = matplotlib.cm.tab20
cmap.set_over('black')
ix = np.random.permutation(np.arange(coords.shape[0], dtype=int))
x = coords[ix, 0]
y = coords[ix, 1]
fig = matplotlib.figure.Figure(figsize=(12, 12))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.scatter(x, y, s=60, alpha=0.8, linewidth=0,
color=cmap(communities[ix]))
ax.tick_params(left='off', labelleft='off', bottom='off', labelbottom='off')
ax.set_title(title)
lbl_rects = [(Circle((0, 0), 1, color=cmap(c)), c) for c in u_community]
fig.legend(*zip(*lbl_rects), **{'handler_map': {Circle: HandlerCircle()},
'loc': 7, 'fontsize': 'large'})
if file_name:
FigureCanvasAgg(fig).print_figure(file_name)
def plot_labelprop_mpl_tissues(coords, tissue_list, file_name=None, title=''):
u_tissue = set(tissue_list)
tissue_d = {t:i for i,t in enumerate(u_tissue)}
cmap = matplotlib.cm.tab20
cmap.set_over('black')
ix = np.random.permutation(np.arange(coords.shape[0], dtype=int))
x = coords[ix, 0]
y = coords[ix, 1]
fig = matplotlib.figure.Figure(figsize=(12, 12))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.scatter(x, y, s=60, alpha=0.8, linewidth=0,
color=[cmap(tissue_d[tissue_list[i]]) for i in ix])
ax.tick_params(left='off', labelleft='off', bottom='off', labelbottom='off')
ax.set_title(title)
lbl_rects = [(Circle((0, 0), 1, color=cmap(tissue_d[t])), t) for t in u_tissue]
fig.legend(*zip(*lbl_rects), **{'handler_map': {Circle: HandlerCircle()},
'loc': 7, 'fontsize': 'large'})
if file_name:
FigureCanvasAgg(fig).print_figure(file_name)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = Circle(xy=center, radius=width / 4.0, alpha=0.4)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
def plot_labelprop_mpl(coords, communities, file_name=None, title=''):
u_community = np.unique(communities)
cmap = matplotlib.cm.tab20
cmap.set_over('black')
ix = np.random.permutation(np.arange(coords.shape[0], dtype=int))
x = coords[ix, 0]
y = coords[ix, 1]
fig = matplotlib.figure.Figure(figsize=(12, 12))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.scatter(x, y, s=60, alpha=0.8, linewidth=0,
color=cmap(communities[ix]))
ax.tick_params(left='off', labelleft='off', bottom='off', labelbottom='off')
ax.set_title(title)
lbl_rects = [(Circle((0, 0), 1, color=cmap(c)), c) for c in u_community]
fig.legend(*zip(*lbl_rects), **{'handler_map': {Circle: HandlerCircle()},
'loc': 7, 'fontsize': 'large'})
if file_name:
FigureCanvasAgg(fig).print_figure(file_name)
def venn2_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the two circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn2()
``kwargs`` are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> c = venn2_circles((1, 2, 3))
>>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect
>>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect
'''
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['10', '01', '11']]
elif len(subsets) == 2:
subsets = compute_venn2_subsets(*subsets)
areas = compute_venn2_areas(subsets, normalize_to)
centers, radii = solve_venn2_circles(areas)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
result = []
for (c, r) in zip(centers, radii):
circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs)
ax.add_patch(circle)
result.append(circle)
return result
def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
>>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14})
>>> plot = venn3_circles([set(['A','B','C']), set(['A','D','E','F']), set(['D','G','H'])])
'''
# Prepare parameters
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']]
elif len(subsets) == 3:
subsets = compute_venn3_subsets(*subsets)
areas = compute_venn3_areas(subsets, normalize_to)
centers, radii = solve_venn3_circles(areas)
if ax is None:
ax = gca()
prepare_venn_axes(ax, centers, radii)
result = []
for (c, r) in zip(centers, radii):
circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs)
ax.add_patch(circle)
result.append(circle)
return result
def __init__(self, center, radius):
self.center = np.asarray(center, float)
self.radius = abs(radius)
if (radius < -tol):
raise VennRegionException("Circle with a negative radius is invalid")
def make_patch(self):
'''
Returns the corresponding circular patch.
>>> patch = VennCircleRegion((1, 2), 3).make_patch()
>>> patch
<matplotlib.patches.Circle object at ...>
>>> patch.center, patch.radius
(array([ 1., 2.]), 3.0)
'''
return Circle(self.center, self.radius)
def plot_circle(ax, x, y, color):
area = 380
circle = ax.scatter(x, y, s=area, c=color)
#edgewidth = 0
#edgecolor = "k" # black
#circle = ax.plot(x, y, "o", c=color, markersize=10)
#circle= mpatches.Circle((x, y), radius, fc=color, ec=edgecolor, lw=edgewidth)
#ax.add_patch(circle)
return circle
def plot_robustness(ax, fpdata, fplabels, fpcolors):
handles = OrderedDict() # for legend
for data, label, color in zip(fpdata, fplabels, fpcolors):
handle = []
# nice painless way to iterate array:
array = np.nditer(data, flags=['multi_index'])
for boolean in array:
if boolean:
i, j = array.multi_index
x, y = X[i], Y[j]
circle = plot_circle(ax, x, y, color)
handle.append(circle)
handles[label] = tuple(handle)
# TODO: axis limits
#ax.set_aspect('equal', 'datalim')
#ax.autoscale_view(True,True,True)
ax.set_xscale("log")#, subsx=[2,5])
ax.set_yscale("log")#, subsy=[2,5])
myhandles = [plt.Rectangle((0, 0), 1, 1, fc=col) for col in fpcolors]
#ax.legend([h[0] for h in handles.values()], handles.keys(),
ax.legend(myhandles, handles.keys(),
#bbox_to_anchor=(0.5, 1.05), loc="lower center", borderaxespad=0.,)
bbox_to_anchor=(0., 1.5), loc="upper left", borderaxespad=0.,)
#handler_map={mpatches.Circle:HandlerPatch(patch_func=make_legend_ellipse)})
ax.set_xlabel("voltage bias [V]")
ax.set_ylabel(r"surface charge density [q/nm$^2$]")
ax.set_xlim(xlim)
ax.set_ylim(ylim)
# --- fixed point ---
def polygon_patches(self, cyl=False):
poly_settings = dict(closed=True, facecolor="#eeeeee", linewidth=1.,
edgecolor="k")
ball_settings = dict(facecolor="#aaaaaa", linewidth=1., edgecolor="k",
alpha=0.5)
ball_bind_zone_settings = dict(facecolor="#ffaaaa", linewidth=0.,
alpha=0.5)
patches = []
for dom in self.domains:
domp = dom.domain
if isinstance(domp, Polygon):
polygon = domp.nodes
polygon = np.array(polygon)
patches.append(mpatches.Polygon(polygon, **poly_settings))
if not cyl:
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
patches.append(mpatches.Polygon(polygon_m, **poly_settings))
elif isinstance(domp, Ball):
xy = domp.x0[0], domp.x0[2]
if dom.binding and dom.bind_type == "zone":
p1 = mpatches.Circle(xy, domp.r + dom.ra,
**ball_bind_zone_settings)
p1.set_zorder(-100)
patches.append(p1)
p = mpatches.Circle(xy, domp.r, **ball_settings)
p.set_zorder(200)
patches.append(p)
return patches
def drawCenter(self):
"""Draws a red marker at selected center on canvas."""
if len(self.centerPt)>0:
self.clearCenter()
pt=ptc.Circle(self.center,radius=3,fill=True,color='r')
self.centerPt.append(self.ax.add_patch(pt))
self.fig.canvas.draw()
return self.centerPt
def drawRadius(self):
"""Draws a red circle around selected center with selected radius on canvas."""
if len(self.radiusPt)>0:
self.clearRadius()
pt=ptc.Circle(self.center,radius=self.radius,fill=False,color='r')
self.radiusPt.append(self.ax.add_patch(pt))
self.fig.canvas.draw()
return self.radiusPt
def showBoundary(self,color=None,linewidth=3,ax=None):
"""Shows ROI in a 2D plot.
If no color is specified, will use color specified in ``ROI.color``.
Keyword Args:
ax (matplotlib.axes): Matplotlib axes used for plotting. If not specified, will generate new one.
color (str): Color of plot.
linewidth (float): Linewidth of plot.
Returns:
matplotlib.axes: Axes used for plotting.
"""
if color==None:
color=self.color
if ax==None:
fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["boundary"],sup=self.name+" boundary")
ax = axes[0]
img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx))
ax.imshow(img)
patch = ptc.Circle(self.center,self.radius,fill=False,linewidth=linewidth,color=color)
ax.add_patch(patch)
return ax
def drawPoint(self,x,y,color='r',idx=0):
pt=ptc.Circle([x,y],radius=3,fill=True,color=color)
self.replaceArtist(idx,self.ax.add_patch(pt))
self.canvas.draw()
return pt
def drawCorner(self,corner):
pt=ptc.Circle([corner[0],corner[1]],radius=3,fill=True,color=self.ROI.color)
self.artists.append(self.ax.add_patch(pt))
return pt
def highlightCorner(self,corner):
c=ptc.Circle([corner[0],corner[1]],radius=6,fill=False,color=self.ROI.color)
self.highlighted=self.ax.add_patch(c)
self.canvas.draw()
return c
def drawPoint(self,x,y,color='r',idx=0):
pt=ptc.Circle([x,y],radius=3,fill=True,color=color)
self.replaceArtist(idx,self.ax.add_patch(pt))
self.canvas.draw()
return pt
def drawCircle(self,center,radius,color='r',idx=1):
c=ptc.Circle(center,radius=radius,fill=False,color=color)
self.replaceArtist(idx,self.ax.add_patch(c))
self.canvas.draw()
return c