我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.Circle()。
def __init__(self,to_plot = True): self.state = np.array([0,0]) self.observation_shape = np.shape(self.get_state())[0] if to_plot: plt.ion() fig = plt.figure() ax1 = fig.add_subplot(111,aspect='equal') #ax1.axis('off') plt.xlim([-0.5,5.5]) plt.ylim([-0.5,5.5]) self.g1 = ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red')) self.fig = fig self.ax1 = ax1 self.fig.canvas.draw() self.fig.canvas.flush_events()
def plot(scheme, show_axes=False): ax = plt.gca() # change default range so that new disks will work plt.axis('equal') ax.set_xlim((-1.5, 1.5)) ax.set_ylim((-1.5, 1.5)) if not show_axes: ax.set_axis_off() disk1 = plt.Circle((0, 0), 1, color='k', fill=False) ax.add_artist(disk1) helpers.plot_disks( plt, scheme.points, scheme.weights, numpy.pi ) return
def plot(scheme, show_axes=False): ax = plt.gca() # change default range so that new disks will work plt.axis('equal') ax.set_xlim((-1.5, 1.5)) ax.set_ylim((-1.5, 1.5)) if not show_axes: ax.set_axis_off() disk1 = plt.Circle((0, 0), 1, color='k', fill=False) ax.add_artist(disk1) # The total area is used to gauge the disk radii. This is only meaningful # for 2D manifolds, not for the circle. What we do instead is choose the # total_area such that the sum of the disk radii equals pi. total_area = numpy.pi**3 / len(scheme.weights) helpers.plot_disks( plt, scheme.points, scheme.weights, total_area ) return
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 debugplot(self, u = None): print 'creating plot...' n = len(self.region['members'][0]) / 2 plt.figure(figsize=(6, n/2*4+1)) m = self.region['members'] d = self.region['maxdistance'] for i in range(n): plt.subplot(numpy.ceil(n / 2.), 2, 1+i) j = i * 2 k = i * 2 + 1 plt.plot(m[:,j], m[:,k], 'x', color='b', ms=1) plt.gca().add_artist(plt.Circle((m[0,j], m[0,k]), d, color='g', alpha=0.3)) if u is not None: plt.plot(u[j], u[k], 's', color='r') plt.gca().add_artist(plt.Circle((u[j], u[k]), d, color='r', alpha=0.3)) prefix='friends%s-%s_' % ('1' if self.jackknife else '', self.metric) plt.savefig(prefix + 'cluster.pdf') plt.close() print 'creating plot... done'
def fovPicker(self): fig = plt.figure() ax = plt.gca() plt.imshow(abs(self.fov)) for n in np.arange(self.positions.shape[0]): circle = plt.Circle(self.positions[n, :], self.probe_radius, color='r', fill=False) ax.add_artist(circle) plt.title("After closing figure, enter desired position for in situ CDI measurement") fig.canvas.draw() index = input("Enter desired position for in situ CDI measurement: ") #print(index) #index = index.astype(int); index = int(index) self.fov_roi = crop_roi(image = self.fov, crop_size = self.arr_size, cenx = self.positions[index,1], ceny = self.positions[index,0]) return self.fov_roi
def plot_eigen_function(ax, se, n, psi1l, psi1r): # plt.figure(figsize=(8, 8)) for x in range(se.info['L']): for y in range(se.info['W']): i = x + y * se.info['L'] w = np.sqrt(10) * np.abs(psi1r[i, n]) arg = np.angle(psi1r[i, n]) circle = plt.Circle((x, y), w, color='black', zorder=10) ax.add_artist(circle) ax.plot([x, x + w * np.cos(arg)], [y, y + w * np.sin(arg)], color='white', lw=.8, zorder=12) ax.set_xlim([-.5, se.info['L'] - .5]) ax.set_ylim([-.5, se.info['W'] - .5]) # plt.show()
def plot_instance_attention(im, instance_points, instance_labels, save_path=None): """ Arguments: im (ndarray): shape = (3, im_width, im_height) the image array instance_points: List of (x, y) pairs the instance's center points instance_labels: List of str the label name of each instance """ fig, ax = plt.subplots() ax.imshow(im) for i, (x_center, y_center) in enumerate(instance_points): label = instance_labels[i] center = plt.Circle((x_center, y_center), 10, color="r", alpha=0.5) ax.add_artist(center) ax.text(x_center, y_center, str(label), fontsize=18, bbox=dict(facecolor="blue", alpha=0.7), color="white") if save_path: if not osp.exists(osp.dirname(save_path)): os.makedirs(osp.dirname(save_path)) fig.savefig(save_path) else: plt.show()
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) circle0 = plt.Circle((dx,dy),0.1) x1, y1 = centroid_com(stamp) circle1 = plt.Circle((x1,y1),0.1,color='r') ax.add_artist(circle1) x2, y2 = centroid_1dg(stamp) circle2 = plt.Circle((x2,y2),0.1,color='b') ax.add_artist(circle2) x3, y3 = centroid_2dg(stamp) circle3 = plt.Circle((x3,y3),0.1,color='g') ax.add_artist(circle3) print(x1, x2, x3) print(y1, y2, y3) # define the directory that contains the images
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) circle0 = plt.Circle((dx,dy),0.1) x1, y1 = centroid_com(stamp) circle1 = plt.Circle((x1,y1),0.1,color='r') ax.add_artist(circle1) x2, y2 = centroid_1dg(stamp) circle2 = plt.Circle((x2,y2),0.1,color='b') ax.add_artist(circle2) x3, y3 = centroid_2dg(stamp) circle3 = plt.Circle((x3,y3),0.1,color='g') ax.add_artist(circle3) return ((x1, y1),(x2, y2),(x3, y3)) #print(x1, x2, x3) #print('now some y values') #print(y1, y2, y3) # define the directory that contains the images
def draw_pred_points(ax, batch_x, pred_points): circles = [] for point_num in range(batch_x.shape[0]): circle = plt.Circle((batch_x[point_num], pred_points[point_num]), 0.005, color='#ff6666') ax.add_artist(circle) plt.pause(0.0000001) circles.append(circle) for circle in circles: circle.remove()
def plot(self): self.g1.remove() self.g1 = self.ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red')) self.fig.canvas.draw() # Test
def plot(self): self.g1.remove() self.g2.remove() self.p.remove() # replot self.g1 = self.ax1.add_artist(plt.Circle(self.ghost1+0.5,0.3,color='red')) self.g2 = self.ax1.add_artist(plt.Circle(self.ghost2+0.5,0.3,color='blue')) self.p = self.ax1.add_artist(plt.Circle(self.pacman +0.5,0.3,color='yellow')) self.fig.canvas.draw()
def plot_fits_for_user_confirmation(self, image): """ Ask user to check if all fits are correct. Clicking on a fit removes it from the results. """ _imshow_style = dict(origin='lower', interpolation='none', cmap=plt.cm.gray) fig_manager = plt.get_current_fig_manager() fig_manager.window.showMaximized() plt.clf() plt.cla() plt.imshow(image, **_imshow_style) for i in UserCheckFits.stored_fits.index: circle = plt.Circle((UserCheckFits.stored_fits.loc[i].x, UserCheckFits.stored_fits.loc[i].y), radius=UserCheckFits.stored_fits.loc[i].r, fc='None', ec='b', ls='solid', lw=0.3, label=i) # Enable picking circle.set_picker(10) plt.gca().add_patch(circle) plt.gca().annotate(i, (UserCheckFits.stored_fits.loc[i].x, UserCheckFits.stored_fits.loc[i].y), color='b', weight='normal', size=8, ha='center', va='center') plt.gca().set_title('Please check the result.' + ' Click on a circle to toggle removal.' + ' Close to confirm.') plt.gcf().canvas.mpl_connect('pick_event', self.on_pick) plt.show(block=True)
def visualize_rboxes(ax, rboxes, colors=None, verbose=False, **kwargs): """ Visualize rotated bounding boxes ARGS ax: pyplot axis rboxes: array [n_rboxes, 5] or [5], (cx, cy, w, h, theta) colors: rboxes colors verbose: print extra information kwargs: extra arguments passed to mpl.patches.Rectangle """ if rboxes.ndim == 1: rboxes = np.expand_dims(rboxes, axis=0) for i in range(rboxes.shape[0]): cx, cy, w, h, theta = rboxes[i] trans = mpl.transforms.Affine2D().rotate_around(cx, cy, theta) + ax.transData ec = 'green' if colors is None else colors[i] rect = mpl.patches.Rectangle((cx - 0.5 * w, cy - 0.5 * h), w, h, facecolor='none', edgecolor=ec, **kwargs) rect.set_transform(trans) ax.add_patch(rect) # c = 'green' if colors is None else colors[i] # center_dot = mpl.patches.Circle((cx, cy), 0.005, color=c) # ax.add_patch(center_dot) if verbose: print('Plotted rbox: (%.2f %.2f %.2f %.2f %.2f)' % (cx, cy, w, h, theta))
def visualize_nodes(ax, node_status, image_size): """ Visualize a grid of nodes with colored dots ARGS `ax`: pyplot axis `node_status`: int [map_h, map_w] `image_size`: int [2] """ map_h, map_w = node_status.shape image_h, image_w = image_size step_x = float(image_w) / map_w step_y = float(image_h) / map_h for p in xrange(map_h * map_w): px, py = p % map_w, p // map_w grid_cx = (0.5 + px) * step_x grid_cy = (0.5 + py) * step_y node_status_p = node_status[py, px] # draw grid center point as a circle if node_status_p == 1: # positive circle_color = 'red' elif node_status_p == 0: # ignore circle_color = 'yellow' elif node_status_p == -1: # negative circle_color = 'blue' else: raise 'Internal error, node_status_p == %d' % node_status_p circle = plt.Circle((grid_cx, grid_cy), 2, color=circle_color) ax.add_artist(circle)
def plot(self): """Plots the charge.""" color = 'b' if self.q < 0 else 'r' if self.q > 0 else 'k' r = 0.1*(sqrt(fabs(self.q))/2 + 1) circle = pyplot.Circle(self.x, r, color=color, zorder=10) pyplot.gca().add_artist(circle)
def _plot_disks_helpers(plt, pts, radii, colors): for tp, radius, color in zip(pts, radii, colors): # highlight circle center plt.plot( [tp[0]], [tp[1]], linestyle='None', marker='.', color=color ) # Choose radius such that the sum of areas of the circles equals # total_area. circ = plt.Circle((tp[0], tp[1]), radius, color=color, alpha=0.5) plt.gca().add_artist(circ) return # pylint: disable=too-many-locals
def __init__(self, center, radius): super(Circle, self).__init__(center) self.radius = float(radius)
def __repr__(self): return "Circle(center={}, radius={})".format(repr(self.center), repr(self.radius))
def patch(self): """Returns a matplotlib patch.""" return plt.Circle((self.center.x, self.center.y), self.radius) # def scale(self, val): # """Scale.""" # raise NotImplementedError # self.center.scale(val) # self.rad *= val
def contains(self, other): """Return whether the Circle contains the other. Return one boolean for all geometric entities. Return an array of boolean for array input. """ if isinstance(other, Point): x = other._x elif isinstance(other, np.ndarray): x = other elif isinstance(other, Circle): return (other.center.distance(self.center) + other.radius <= self.radius) elif isinstance(other, Polygon): x = _points_to_array(other.vertices) return np.all(self.contains(x)) elif isinstance(other, Mesh): for face in other.faces: if not self.contains(face): return False return True else: raise NotImplementedError("Circle.contains() not implemented for" + " {}".format(type(other))) return np.sum((x - self.center._x)**2, axis=1) <= self.radius**2
def contains(self, other): """Return whether this Polygon contains the other.""" border = Path(self.numpy) if isinstance(other, Point): x = other._x elif isinstance(other, np.ndarray): x = other elif isinstance(other, Polygon): x = _points_to_array(other.vertices) return np.all(border.contains_points(x, radius=1e-32)) elif isinstance(other, Circle): if self.contains(other.center): for edge in self.edges: if other.center.distance(edge) < other.radius: return False return True return False elif isinstance(other, Mesh): for face in other.faces: if not self.contains(face): return False return True else: raise NotImplementedError("Polygon.contains() not implemented " + "for this class.") border = Path(self.numpy) return border.contains_points(np.atleast_2d(x), radius=1e-32)
def draw(self, fill=False): circle = plt.Circle((self.x, self.y), radius=1, fill=fill) plt.gca().add_patch(circle)
def draw(self, fill=False): y=self.y+0.5 for i in range(3): circle = plt.Circle((self.x, y), radius=0.1, fill="0") plt.gca().add_patch(circle) y += 0.4
def plot(self, fig=None, ax=None): xy = self.xy[:, :] xymax = np.max(xy, axis=0) xymin = np.min(xy, axis=0) # imin = [np.where(xy[:, i] == xymin[i])[0] for i in xrange[2]] xy -= np.reshape(np.tile(.5 * (xymax + xymin), self.N), (self.N, 2)) xyscale = np.max((xymax - xymin) / 100) show = False if fig is None or ax is None: show = True fig, ax = plt.subplots(figsize=(4, 4)) for link in self.links: ax.plot(xy[link[0:2], 0] / xyscale, xy[link[0:2], 1] / xyscale, 'b') for i in xrange(self.N): x, y = xy[i, 0:2] / xyscale circle = plt.Circle((x, y), 3, color='#e5e5e5', zorder=10) ax.add_artist(circle) ax.text(x, y + 1, '{0}'.format(i), zorder=20, ha='center', va='center') ax.set_xlim([-60, 60]) ax.set_ylim([-60, 60]) if show is True: plt.show()
def get_curvature(nodes, s, tangent_vec, curvature): """Image for :func:`get_curvature` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) # Find the center of the circle along the direction # perpendicular to the tangent vector (90 degree left turn). radius_dir = np.asfortranarray([[-tangent_vec[0, 1], tangent_vec[0, 0]]]) radius_dir /= np.linalg.norm(radius_dir, ord=2) point = curve.evaluate(s) circle_center = point + radius_dir / curvature # Add the curve. ax = curve.plot(256) # Add the circle. circle_center = circle_center.flatten() circle = plt.Circle(circle_center, 1.0 / abs(curvature), alpha=0.25) ax.add_artist(circle) # Add the point. ax.plot(point[:, 0], point[:, 1], color='black', marker='o', linestyle='None') ax.axis('scaled') ax.set_xlim(-0.0625, 1.0625) ax.set_ylim(-0.0625, 0.625) save_image(ax.figure, 'get_curvature.png')
def _draw_graph_diffing(graph1, graph2, differences): plt.subplot(121) pos = nx.pygraphviz_layout(graph1, prog='dot') nx.draw_networkx_nodes(graph1, pos, graph1.nodes(), node_color='b', node_size=200) nx.draw_networkx_nodes(graph1, pos, differences[0], node_color='r', node_size=600) nx.draw_networkx_nodes(graph1, pos, differences[2], node_color='y', node_size=600) nx.draw_networkx_edges(graph1, pos, graph1.edges()) nx.draw_networkx_labels(graph1, pos, font_size=8) plt.title('Graph 1') plt.axis('off') plt.subplot(122) pos = nx.pygraphviz_layout(graph2, prog='dot') nx.draw_networkx_nodes(graph2, pos, graph2.nodes(), node_color='b', node_size=200) nx.draw_networkx_nodes(graph2, pos, differences[1], node_color='r', node_size=600) nx.draw_networkx_nodes(graph2, pos, differences[3], node_color='g', node_size=600) nx.draw_networkx_edges(graph2, pos, graph2.edges()) nx.draw_networkx_labels(graph2, pos, font_size=8) plt.title('Graph 2') plt.axis('off') lr = plt.Circle((0, 0), 5, fc='r') lb = plt.Circle((0, 0), 5, fc='b') lg = plt.Circle((0, 0), 5, fc='g') ly = plt.Circle((0, 0), 5, fc='y') plt.legend([lb, lr, lg, ly], ['No changed', 'Changed', 'Added', 'Removed'], loc=4) # plt.savefig(graph1.name + '-' + graph2.name + '.png') plt.show()
def make_alert_img(color, type1, outfolder): """ Construct alert image. Args: color (str): Alert color. type1 (str): Alert type, indicating landslide vs liquefaction. outfolder (str): Path for output file. Returns: str: Output file name. """ if color is None: outfilename = None else: fig = plt.figure(figsize=(6, 1.8)) ax = fig.add_subplot(111) ax.add_artist(plt.Circle((0.4, 0.3), 0.15, facecolor=color, edgecolor='black', lw=1)) ax.text(0.7, 0.25, '%s alert %s' % (type1.title(), color), fontsize=25) ax.axis('off') ax.set_xlim([0, 2.0]) ax.set_ylim([0., 0.6]) plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02) outfilename = os.path.join(outfolder, '%s_alert.png' % type1) fig.savefig(outfilename, transparent=True) plt.close() return outfilename
def plot_pole_zero(self, filename=None): """Produce a plot with the location of all poles and zeros.""" zeros, poles, gain = scipy.signal.tf2zpk(self._B, self._A) self._logger.debug("zeros: %s" %zeros) self._logger.debug("poles: %s" %poles) self._logger.debug("gain : %s" %gain) fig = plt.figure(1) ax = fig.add_subplot(111, aspect='equal') circ = plt.Circle((0,0), radius=1, fill=False, color='black', linestyle='dashed', linewidth=1.0) ax.add_patch(circ) ax.axhline(0, linestyle='dashed', color='black', linewidth=1.0) ax.axvline(0, linestyle='dashed', color='black', linewidth=1.0) ax.grid(True) ax.plot(poles.real, poles.imag, marker='x', ms=7.0, mew=1.5, mfc='blue', mec='blue', ls='None', label='poles (%i)' %len(poles)) ax.plot(zeros.real, zeros.imag, marker='o', ms=7.0, mew=1.5, mfc='None', mec='red', ls='None', label='zeros (%i)' %len(zeros)) ax.margins(0.1) # TODO: count multiples at (0,0) plt.legend(loc='best', numpoints=1) plt.title('Pole-zero locations') plt.xlabel('Real') plt.ylabel('Imaginary') if filename is None: plt.show() else: try: plt.savefig(filename) finally: plt.close(1)
def generate_report(): # The slices will be ordered and plotted counter-clockwise. labels = ['groceries', 'entertainment', 'books', 'shopping'] b = random.randint(2, 98) a = random.randint(1, b - 1) c = random.randint(b + 1, 99) percents = [a, b - a, c - b, 100 - c] print percents colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0, 0, 0) # explode a slice if required plt.pie(percents, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False) #draw a circle at the center of pie to make it look like a donut centre_circle = plt.Circle((0,0),0.75,color='black', fc='white',linewidth=1.25) fig = plt.gcf() fig.gca().add_artist(centre_circle) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') fig_name = 'foo{}'.format(random.randint(1,1000000000000)) max_per = max(percents) to_watch = labels[percents.index(max_per)] #### uncomment out when needed fig.savefig(fig_name, dpi=300) return fig_name, to_watch # return "you should watch your spending on {}".format(to_watch) # return fig_name, (max_per, to_watch)
def plot_synthetic_spatial_layout(self): radius = 5 positions = self.probe.positions cells_radius = 7 cells_positions = self.gen.get(variables=['x', 'y']) x_min = np.min(positions[0, :]) - float(radius) x_max = np.max(positions[0, :]) + float(radius) x_pad = 0.2 * (x_max - x_min) y_min = np.min(positions[1, :]) - float(radius) y_max = np.max(positions[1, :]) + float(radius) y_pad = 0.2 * (x_max - x_min) plt.style.use('seaborn-paper') plt.figure() ax = plt.gca() # Plot the tips of the electrodes. for k in range(self.probe.nb_channels): x, y = positions[:, k] c = plt.Circle((x, y), radius=radius, facecolor='gray', edgecolor='black') ax.add_artist(c) # Plot the cells. for k in range(0, self.gen.nb_cells): x, y = [cells_positions[str(k)][key][0] for key in ['x', 'y']] c = plt.Circle((x, y), radius=cells_radius, color='C{}'.format(k)) ax.add_artist(c) plt.axis('scaled') plt.xlim(x_min - x_pad, x_max + x_pad) plt.ylim(y_min - y_pad, y_max + y_pad) plt.xlabel("x (µm)") plt.ylabel("y (µm)") plt.title("Synthetic spatial layout") plt.tight_layout() plt.show() return
def getMarkerList(self, filter="", valuesDict=None, typeId="", targetId=0): """Returns a list of marker styles.""" self.logger.debug(u"{0:*^40}".format(' Get Marker List ')) if self.verboseLogging: self.logger.threaddebug(u"filter = {0} typeId = {1} targetId = {2}".format(filter, typeId, targetId)) self.logger.threaddebug(u"valuesDict: {0}".format(dict(valuesDict))) return [ ("None", "None"), ("o", "Circle"), ("D", "Diamond"), ("d", "Diamond (Thin)"), ("h", "Hexagon 1"), ("H", "Hexagon 2"), ("-", "Horizontal Line"), ("8", "Octagon"), ("p", "Pentagon"), ("PIX", "Pixel"), ("+", "Plus"), (".", "Point"), ("*", "Star"), ("s", "Square"), ("v", "Triangle Down"), ("TL", "Triangle Left"), ("TR", "Triangle Right"), ("1", "Tri Down"), ("2", "Tri Up"), ("3", "Tri Left"), ("4", "Tri Right"), ("|", "Vertical Line"), ("x", "X") ]
def IMshow_pupil(pupil_raw, axnum = True, c_scale = None, crop = None, inner_diam= None, cbo = 'horizontal'): ''' display a pupil function in 2D ''' pupil = np.copy(pupil_raw) NY, NX = pupil.shape ry = int(NY/2.) rx = int(NX/2.) # print(rx, ry) yy = (np.arange(NY)-ry)/ry xx = (np.arange(NX)-rx)/rx if (cbo == 'horizontal'): fig = plt.figure(figsize=(3.0,3.4)) else: fig = plt.figure(figsize=(3.5,3.0)) ax = fig.add_subplot(111) [MX, MY] = np.meshgrid(xx,yy) ax.set_ylim([-1, 1]) ax.set_xlim([-1, 1]) if crop is not None: cropped = np.sqrt(MX**2+MY**2)> crop pupil[cropped] = 0 if (axnum == False): ax.get_yaxis().set_visible(False) ax.get_xaxis().set_visible(False) # fig.axes.get_yaxis().set_visible(False) if(c_scale is None): pcm = ax.pcolor(MX, MY, pupil, cmap = 'RdYlBu_r') cbar = fig.colorbar(pcm, ax = ax, extend = 'max' , orientation= cbo) cbar.ax.tick_params(labelsize = 12) else: pcm = ax.pcolor(MX, MY, pupil, cmap = 'RdYlBu_r',vmin = c_scale[0], vmax = c_scale[1]) cbar = fig.colorbar(pcm, ax = ax, extend = 'max' , orientation = cbo, pad = 0.04) cbar.ax.tick_params(labelsize = 12) if(inner_diam is not None): cmark = plt.Circle((0,0), inner_diam, color= 'w', ls = '--', linewidth = 2, fill = False) ax.add_artist(cmark) plt.tight_layout() return fig # return the figure handle
def __init__(self, ax, radius, **circprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.storebg) circprops['animated'] = True circprops['radius'] = radius self.circ = plt.Circle((0,0), **circprops) self.ax.add_artist(self.circ) self.background = None
def plotCircle(x,y,radius,color, alphaval): circle = plt.Circle((x, y), radius=radius, fc=color, alpha=alphaval) fig.gca().add_patch(circle) nofcircle = plt.Circle((x, y), radius=radius, ec=color, fill=False) fig.gca().add_patch(nofcircle)
def define_quadrotor(self): # Create the square cells for local sensing range of the quadrotor # In quad_cells[i][j], 'cell' gives the object, 'text' gives the text on the cell cell_cmd = "plt.Rectangle((0, 0), 1, 1, edgecolor = 'black', fill=False, linewidth = 0.5)" self.quad_cells = [[dict() for y in range(0, self.quad.sensing_range)] for x in range(0, self.quad.sensing_range)] for x,y in it.product(range(0, self.quad.sensing_range), repeat=2): self.quad_cells[x][y] = {'cell': eval(cell_cmd), 'text': self.ax.text(0.5,0.5,'X',fontsize=10,ha='center',va='center',weight='bold')} self.ax.add_artist(self.quad_cells[x][y]['cell']) # Create circles for drawing the quad (0.20 radius) blade_cmd = 'plt.Circle((0,0),0.20,fill=False,linewidth=1)' self.quad_blades = [None]*4 for i in range(0,4): self.quad_blades[i] = eval(blade_cmd) self.ax.add_artist(self.quad_blades[i])
def findVoxInHist(self, event): """Find voxel's location in histogram.""" self.press = event.xdata, event.ydata pixel_x = int(np.floor(event.xdata)) pixel_y = int(np.floor(event.ydata)) aoi = self.invHistVolume[:, :, self.sliceNr] # array of interest # Check rotation (TODO: code repetition!) cyc_rot = self.cycRotHistory[self.cycleCount][1] if cyc_rot == 1: # 90 aoi = np.rot90(aoi, axes=(0, 1)) elif cyc_rot == 2: # 180 aoi = aoi[::-1, ::-1] elif cyc_rot == 3: # 270 aoi = np.rot90(aoi, axes=(1, 0)) # Switch x and y voxel to get linear index since not Cartesian!!! pixelLin = aoi[pixel_y, pixel_x] # ind2sub xpix = (pixelLin / self.nrBins) ypix = (pixelLin % self.nrBins) # Switch x and y for circle centre since back to Cartesian. circle_colors = [np.array([8, 48, 107, 255])/255, np.array([33, 113, 181, 255])/255] self.highlights[0].append(plt.Circle((ypix, xpix), radius=1, edgecolor=None, color=circle_colors[0])) self.highlights[1].append(plt.Circle((ypix, xpix), radius=5, edgecolor=None, color=circle_colors[1])) self.axes.add_artist(self.highlights[0][-1]) # small circle self.axes.add_artist(self.highlights[1][-1]) # large circle self.figure.canvas.draw()
def __init__(self,to_plot=True,grid=False): world = np.zeros([7,7],dtype='int32') world[1:6,1] = 1 world[1:3,4] = 1 world[4:6,4] = 1 self.world = world self.grid = grid self.reset() self.observation_shape = np.shape(self.get_state())[0] if to_plot: plt.ion() fig = plt.figure() ax1 = fig.add_subplot(111,aspect='equal') ax1.axis('off') plt.xlim([-1,8]) plt.ylim([-1,8]) #colors = matplotlib.colors.ListerColormap() for i in range(7): for j in range(7): if world[i,j]==1: col = "black" else: col = "white" ax1.add_patch( patches.Rectangle( (i,j),1,1, #fill=False, edgecolor='black', linewidth = 2, facecolor = col,), ) if np.all([i,j] == self.ghost1): self.g1 = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='red')) if np.all([i,j] == self.ghost2): self.g2 = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='blue')) if np.all([i,j] == self.pacman): self.p = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='yellow')) self.fig = fig self.ax1 = ax1 self.fig.canvas.draw()
def draw_neural_net(self, ax, left, right, bottom, top, layer_sizes): ''' Draw a neural network cartoon using matplotilb. :usage: >>> fig = plt.figure(figsize=(12, 12)) >>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2]) :parameters: - ax : matplotlib.axes.AxesSubplot The axes on which to plot the cartoon (get e.g. by plt.gca()) - left : float The center of the leftmost node(s) will be placed here - right : float The center of the rightmost node(s) will be placed here - bottom : float The center of the bottommost node(s) will be placed here - top : float The center of the topmost node(s) will be placed here - layer_sizes : list of int List of layer sizes, including input and output dimensionality ''' n_layers = len(layer_sizes) + 1 maxLayerSize = 0 for layer_group in layer_sizes: layer_size = sum(map(lambda x: x[1], layer_group)) maxLayerSize = max(maxLayerSize, layer_size) v_spacing = (top - bottom)/float(maxLayerSize) h_spacing = (right - left)/float(len(layer_sizes) - 1) # Nodes for layerIndex, layer_group in enumerate(layer_sizes): layer_size = sum(map(lambda x: x[1], layer_group)) layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2. currentIndex = 0 for functionIndex, (inputSize, outputSize) in enumerate(layer_group): if outputSize > 0: for nodeIndex in range(outputSize): circle = plt.Circle((layerIndex*h_spacing + left, layer_top - currentIndex*v_spacing), v_spacing/4., color=self.activationFunctionColors[functionIndex], ec='k', zorder=4) ax.add_artist(circle) currentIndex += 1 else: # Null nodes, ignore and keep going continue """ # Edges for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])): layer_top_a = v_spacing*(layer_size_a - 1)/2. + (top + bottom)/2. layer_top_b = v_spacing*(layer_size_b - 1)/2. + (top + bottom)/2. for m in xrange(layer_size_a): for o in xrange(layer_size_b): line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left], [layer_top_a - m*v_spacing, layer_top_b - o*v_spacing], c='k') ax.add_artist(line) """
def correlation_circle(self, axes, column_correlations, supplementary_column_correlations, explained_inertia, show_labels): fig, ax = plt.subplots() ax.grid('on') ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.axhline(y=0, linestyle='--', linewidth=1.2, color=GRAYS['dark'], alpha=0.6) ax.axvline(x=0, linestyle='--', linewidth=1.2, color=GRAYS['dark'], alpha=0.6) # Plot the arrows and add text for _, row in column_correlations.iterrows(): ax.annotate( row.name if show_labels else '', xy=(0, 0), xytext=(row[axes[0]], row[axes[1]]), arrowprops=dict(arrowstyle='<-', edgecolor='black') ) if not supplementary_column_correlations.empty: for _, row in supplementary_column_correlations.iterrows(): ax.annotate( row.name if show_labels else '', xy=(0, 0), xytext=(row[axes[0]], row[axes[1]]), arrowprops=dict(arrowstyle='<-', edgecolor='red') ) # Add legend to distinguish active and supplementary columns active_legend = mpatches.Patch(color='black', label='Active columns') supp_legend = mpatches.Patch(color='red', label='Supplementary columns') plt.legend(handles=[active_legend, supp_legend]) circle = plt.Circle((0, 0), radius=1, color=GRAYS['dark'], fill=False, lw=1.4) ax.add_patch(circle) ax.margins(0.01) ax.axis('equal') ax.set_title('Correlation circle') ax.set_xlabel('Component {} ({}%)'.format(axes[0], 100 * round(explained_inertia[axes[0]], 2))) ax.set_ylabel('Component {} ({}%)'.format(axes[1], 100 * round(explained_inertia[axes[1]], 2))) return fig, ax
def draw_system(ax, a_rs=3., rp_rs=0.5, theta=None, rs=0.1, xs=(0.5, 0.5), label_radii=True, draw_planet=True, draw_sun=True, planet_circle_kwargs=dict(color='0.7'), sun_circle_kwargs=dict(color='r', alpha=0.5), draw_a=True, a_kwargs=dict(color='k', ls='-'), label_a=True): if theta is None: theta = theta_entry(a_rs=a_rs, rp_rs=rp_rs) xp = circ_pos(xs, theta, a_rs * rs) if draw_planet: planet = plt.Circle(xp, rp_rs * rs, **planet_circle_kwargs) ax.add_artist(planet) if draw_sun: star = plt.Circle(xs, rs, **sun_circle_kwargs) ax.add_artist(star) ax.plot([xs[0] - rs, xs[0] - rs], [0, xs[1]], color='k', ls=':') ax.plot([xs[0] + rs, xs[0] + rs], [0, xs[1]], color='k', ls=':') if draw_a: ax.plot(*zip(xs, xp), **a_kwargs) if draw_a and label_a: atext_xy = tuple(0.5 * (np.array(xs) + np.array(xp))) acoords = (-5 * np.cos(theta), -5 * np.sin(theta)) ax.annotate("$a$", xy=atext_xy, xytext=acoords, textcoords='offset points', xycoords='data', ha='right', va='bottom' if theta < 0 else 'top', fontsize=20) if label_radii: ax.plot([xs[0], xs[0] + rs], [xs[1], xs[1]], ls='--', color='k') ax.annotate("$R_{\\star}$", xy=(xs[0] + 0.5 * rs, xs[1]), xytext=(0, 3), textcoords='offset points', xycoords='data', ha='center', va='bottom', fontsize=20) ax.plot([xp[0], xp[0] - rs * rp_rs], [xp[1], xp[1]], ls='--', color='k') ax.annotate("$R_p$", xy=(xp[0] - 0.5 * rs * rp_rs, xp[1]), xytext=(-5, -5), textcoords='offset points', xycoords='data', ha='right', va='top', fontsize=20)
def plot_wigner_plaquette(wigner_data, max_wigner='local'): """Plots plaquette of wigner function data, the plaquette will consist of cicles each colored to match the value of the Wigner function at the given point in phase space. Args: wigner_data (matrix): array of Wigner function data where the rows are plotted along the x axis and the columns are plotted along the y axis max_wigner: - 'local' puts the maximum value to maximum of the points - 'unit' sets maximum to 1 - float for a custom maximum. Returns: none: plot is shown with matplotlib to the screen """ wigner_data = np.matrix(wigner_data) dim = wigner_data.shape if max_wigner == 'local': w_max = np.amax(wigner_data) elif max_wigner == 'unit': w_max = 1 else: w_max = max_wigner # For a float input cmap = plt.cm.get_cmap('seismic_r') xax = dim[1]-0.5 yax = dim[0]-0.5 norm = np.amax(dim) fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm)) ax = fig.gca() for x in range(int(dim[1])): for y in range(int(dim[0])): circle = plt.Circle( (x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max))) ax.add_artist(circle) ax.set_xlim(-1, xax+0.5) ax.set_ylim(-1, yax+0.5) ax.set_xticks([], []) ax.set_yticks([], []) m = cm.ScalarMappable(cmap=cm.seismic_r) m.set_array([-w_max, w_max]) plt.colorbar(m, shrink=0.5, aspect=10) plt.show()
def plane_eigenbasis(t=1, parasite=0, phase=0, n=0, Es=None, directory=""): """analyze""" se = plane.UniformPlane(L=8, W=8, js=(0, 8 * 7), E=0, t=t, U=0, phase=phase, parasite=parasite) print(se.model.links) # E1, psi1l, psi1r = se.eigenbasis(1) E1, psi1l, psi1r = eigenbasis(se, 1) # sort # print(E1) idx = np.argsort(np.real(E1)) E1 = E1[idx] psi1l = psi1l[:, idx] psi1r = psi1r[:, idx] f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3)) ax1.plot(np.real(E1), np.imag(E1), 'o') ax1.plot(np.real(E1[n]), np.imag(E1[n]), 'o', color='red') ax2.plot(np.real(E1), [np.angle(psi1l[0, i] / psi1l[1, i]) for i in np.arange(64)], 'o') ax2.plot(np.real(E1[n]), np.angle(psi1l[0, n] / psi1l[1, n]), 'o', color='red') plt.show() def plot_weights(ax, se, n, psi1l, psi1r): for x in range(se.info['L']): for y in range(se.info['W']): i = x + y * se.info['L'] w = psi1r[i, n].conjugate() * psi1l[i, n] circle = plt.Circle((x, y), np.abs(w) * 10, color='black', zorder=10) ax.add_artist(circle) # ax.text(x, y, '{0}'.format(x + y * se.info['L']), zorder=20, ha='center', va='center', color="#e5e5e5") ax.set_xlim([-.5, se.info['L'] - .5]) ax.set_ylim([-.5, se.info['W'] - .5]) fig = plt.figure(figsize=(8, 8)) for n in range(se.info['L']): for m in range(se.info['W']): l = n + m * se.info['L'] ax = plt.subplot(se.info['L'], se.info['W'], l + 1) plot_eigen_function(ax, se, l, psi1l, psi1r) plt.show()
def plot_IA_radius(IA_set, radius, size=(1000,1200), surface_image=None, annotated=True): """Plots a circle with radius r around the center of each interest area. Optionally, one can provide a surface_image to draw the IAs on. Parameters ---------- IA_set : sequence of InterestArea objects The Interest areas to plot. size : tuple, default (1000,1200) The space to plot the fixations in. The fixation coordinates inside a surface are normalized by the pupil eye tracker so dimensions need to be specified to be able to plot them. surface_image : string, default None: Path to the image to use as the background of the fixation plot Raises ------ TypeError : if surface_image is not a string to an image IOError : if image is not found at specified path """ scaler = (size[0]/1000.0, size[1]/1200.0) plt.figure(figsize=(size[0]/200, size[1]/200)) plt.xlim(0,size[0]) plt.ylim(0,size[1]) # First check if image location is specified and exists as a file. if not surface_image is None: if not type(surface_image) == str: raise TypeError("surface_image must be a path to the image") else: if not (os.path.isfile(surface_image) and os.access(surface_image, os.R_OK)): raise IOError("Image file not found at path or is unreadable (check permissions)") else: # Flip image upside down im = plt.imread(surface_image) plt.imshow(im, aspect='auto', extent=[0,size[0], 0, size[1]]) gcf = plt.gcf() for ia in IA_set: x,y = ia.get_center() x *= scaler[0] y *= scaler[1] circle=plt.Circle((x,y),radius, color=random.choice(['r','g','b','y']), clip_on=False) circle.set_alpha(0.25) gcf.gca().add_artist(circle) if annotated: plt.annotate(ia.label, xy=(x,y), xytext=(-len(ia.label)*2,0), textcoords = 'offset points') plt.show()
def plotPlate(selection, selectioncolors, platename): inch = 25.4 radius = 4.5/inch # diameter of 96 well plates is 9mm radiusc = 4/inch circles = dict() rows = 8 cols = 12 colsStr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] rowsStr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] rowsStr = rowsStr[::-1] fig = plt.figure(frameon=False) fig.set_size_inches(5, 8) ax = plt.Axes(fig, [0., 0., 1., 1.],) ax.set_axis_off() fig.add_axes(ax) ax.cla() plt.axis('equal') for xcord in range(0, cols): for ycord in range(0, rows): string = rowsStr[ycord]+colsStr[xcord] xpos = xcord*radius*2+radius ypos = ycord*radius*2+radius if string in selection: # circle = plt.Circle((xpos, ypos), radiusc, facecolor='black', edgecolor='black') circle = plt.Circle((xpos, ypos), radiusc, facecolor=selectioncolors[selection.index(string)], edgecolor='black') ax.text(xpos, ypos, string, fontsize=10, color='white', horizontalalignment='center', verticalalignment='center') else: circle = plt.Circle((xpos, ypos), radiusc, facecolor='white', edgecolor='black') ax.add_artist(circle) # inner rectangle ax.add_patch(patches.Rectangle((0, 0), cols*2*radius, rows*2*radius, fill=False)) # outer Rectangle ax.add_patch(patches.Rectangle((0-2*radius, 0), (cols+1)*2*radius, (rows+1)*2*radius, fill=False)) # add rows and columns for xcord in range(0, cols): ax.text(xcord*2*radius+radius, rows*2*radius+radius, colsStr[xcord], fontsize=10, color='black', horizontalalignment='center', verticalalignment='center') for ycord in range(0, rows): ax.text(-radius, ycord*2*radius+radius, rowsStr[ycord], fontsize=10, color='black', horizontalalignment='center', verticalalignment='center') ax.set_xlim([-2*radius, cols*2*radius]) ax.set_ylim([0, (rows+1)*2*radius]) plt.title(platename+' - '+str(len(selection))+' Staples') ax.set_xticks([]) ax.set_yticks([]) xsize = 13*2*radius ysize = 9*2*radius fig.set_size_inches(xsize, ysize) return fig
def vis_all_detection(im_array, detections, class_names, scale, head_boxes=None, joints=None): """ visualize all detections in one image :param im_array: [b=1 c h w] in rgb :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ] :param class_names: list of names in imdb :param scale: visualize the scaled image :return: """ import matplotlib.pyplot as plt import random im = image.transform_inverse(im_array, config.PIXEL_MEANS) plt.imshow(im) for j, name in enumerate(class_names): if name == '__background__': continue color = (random.random(), random.random(), random.random()) # generate a random color dets = detections[j] for det in dets: bbox = det[:4] * scale score = det[-1] rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=3.5) plt.gca().add_patch(rect) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(name, score), bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white') if head_boxes is not None: color = (random.random(), random.random(), random.random()) # generate a random color for det in head_boxes: bbox = det[:4] * scale rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=3.5) plt.gca().add_patch(rect) if joints is not None: color = (random.random(), random.random(), random.random()) # generate a random color for joint in joints: joint *= scale for (cx, cy) in zip(joint[0::2], joint[1::2]): ptr = plt.Circle((cx, cy), 5.0, color=color) plt.gca().add_artist(ptr) plt.show()
def _gen_cell_r0(bd_on=True, rand_pos_cell=False, r_cell=0.1, # 0<r_cell<=1 r_bd=0.05, # 0<r_bd<=1 max_bd=5, # max_bd >= 1 bound_flag=True, visible=False, disp=False, fig=None, ax=None): """ Generate cell images """ if fig is None or ax is None: assert fig is None and ax is None fig, ax = plt.subplots(figsize=(2, 2)) # set_axis_bgcolor is not working because of plt.axis('off') # ax.set_axis_bgcolor('red') close_fig_flag = True else: close_fig_flag = False fig.patch.set_facecolor('black') circle_d = {} if rand_pos_cell: if bound_flag: # Not generate cells in the boundary B = r_cell + 2.0 * r_bd pos_cell = B + (1.0 - 2 * B) * np.random.random(2) else: pos_cell = np.random.random(2) else: pos_cell = np.array([0.5, 0.5]) def rand_pos_bd(): th = np.random.random() * 2 * np.pi pos_bd = pos_cell + (r_cell + r_bd) * \ np.array((np.cos(th), np.sin(th))) return pos_bd #print( pos_cell, pos_bd) circle_d["cell"] = plt.Circle(pos_cell, r_cell, color='w') if bd_on: for bd_n in range(np.random.randint(max_bd)+1): circle_d["bd{}".format(bd_n)] = plt.Circle(rand_pos_bd(), r_bd, color='w') # circle_d["bd2"] = plt.Circle(rand_pos_bd(), r_bd, color='w') for k in circle_d.keys(): ax.add_artist(circle_d[k]) plt.axis('off') data_a = fig2array(fig) if disp: print("Image array shape = ", data_a.shape) if visible: plt.show() else: if close_fig_flag: plt.close() else: plt.cla() return data_a