def test_patch_str(): """ Check that patches have nice and working `str` representation. Note that the logic is that `__str__` is defined such that: str(eval(str(p))) == str(p) """ p = mpatches.Circle(xy=(1, 2), radius=3) assert str(p) == 'Circle(xy=(1, 2), radius=3)' p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5) assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)' p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5) assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)' p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6) assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)' p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7) expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)' assert str(p) == expected p = mpatches.RegularPolygon((1, 2), 20, radius=5) assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)" p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20) assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)" p = mpatches.FancyBboxPatch((1, 2), width=3, height=4) assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)" # Further nice __str__ which cannot be `eval`uated: path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO), ([1, 2], mpath.Path.CLOSEPOLY)] p = mpatches.PathPatch(mpath.Path(*zip(*path_data))) assert str(p) == "PathPatch3((1, 2) ...)" data = [[1, 2], [2, 2], [1, 2]] p = mpatches.Polygon(data) assert str(p) == "Polygon3((1, 2) ...)" p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data))) assert str(p)[:27] == "FancyArrowPatch(Path(array(" p = mpatches.FancyArrowPatch((1, 2), (3, 4)) assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))" p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data') assert str(p) == "ConnectionPatch((1, 2), (3, 4))" s = mpatches.Shadow(p, 1, 1) assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"
def __spring_support_patch(self, max_val): """ :param max_val: max scale of the plot """ h = PATCH_SIZE * max_val left = -0.5 * h right = 0.5 * h dh = 0.2 * h for node, _ in self.system.supports_spring_z: yval = np.arange(0, -9, -1) * dh + node.vertex.y xval = np.array([0, 0, left, right, left, right, left, 0, 0 ]) + node.vertex.x self.one_fig.plot(xval, yval, color='r', zorder=10) # Triangle support_patch = mpatches.RegularPolygon( (node.vertex.x, -node.vertex.z - h * 2.6), numVertices=3, radius=h * 0.9, color='r', zorder=10) self.one_fig.add_patch(support_patch) for node, _ in self.system.supports_spring_x: xval = np.arange(0, 9, 1) * dh + node.vertex.x yval = np.array([0, 0, left, right, left, right, left, 0, 0 ]) + node.vertex.y self.one_fig.plot(xval, yval, color='r', zorder=10) # Triangle support_patch = mpatches.RegularPolygon( (node.vertex.x + h * 1.7, -node.vertex.z - h), numVertices=3, radius=h * 0.9, color='r', zorder=10) self.one_fig.add_patch(support_patch)
def legend_artist(self, legend, orig_handle, fontsize, handlebox): x0, y0 = handlebox.xdescent + handlebox.width / 3, handlebox.ydescent + handlebox.height / 3 width = height = handlebox.height patch = mpatches.RegularPolygon( (x0, y0), numVertices=6, radius=0.7 * handlebox.height, orientation=np.deg2rad(30), facecolor=mcolors.to_rgb('brown') + (0.5, ), edgecolor=mcolors.to_rgb('black') + (1, ), transform=handlebox.get_transform()) handlebox.add_artist(patch) return patch
def draw_regular_hexagon(plt, ticker): plt.axis('scaled') plt.xlim(0, 12) plt.ylim(0, 10) draw_fine_grid(plt, ticker) hexagon = patches.RegularPolygon( (5, 5), # (x,y) 6, # number of vertices 3, # radius facecolor='y', fill=True) plt.gca().add_patch(hexagon) plt.show()
def __hinged_support_patch(self, max_val): """ :param max_val: max scale of the plot """ radius = PATCH_SIZE * max_val for node in self.system.supports_hinged: support_patch = mpatches.RegularPolygon( (node.vertex.x, node.vertex.y - radius), numVertices=3, radius=radius, color='r', zorder=9) self.one_fig.add_patch(support_patch)
def __roll_support_patch(self, max_val): """ :param max_val: max scale of the plot """ radius = PATCH_SIZE * max_val count = 0 for node in self.system.supports_roll: direction = self.system.supports_roll_direction[count] x1 = np.cos(np.pi) * radius + node.vertex.x + radius z1 = np.sin(np.pi) * radius + node.vertex.y x2 = np.cos(np.radians(90)) * radius + node.vertex.x + radius z2 = np.sin(np.radians(90)) * radius + node.vertex.y x3 = np.cos(np.radians(270)) * radius + node.vertex.x + radius z3 = np.sin(np.radians(270)) * radius + node.vertex.y triangle = np.array([[x1, z1], [x2, z2], [x3, z3]]) if node.id in self.system.inclined_roll: angle = self.system.inclined_roll[node.id] triangle = rotate_xy(triangle, angle + np.pi * 0.5) support_patch = plt.Polygon(triangle, color='r', zorder=9) self.one_fig.add_patch(support_patch) self.one_fig.plot( triangle[1:, 0] - 0.5 * radius * np.sin(angle), triangle[1:, 1] - 0.5 * radius * np.cos(angle), color='r') elif direction == 2: # horizontal roll support_patch = mpatches.RegularPolygon( (node.vertex.x, node.vertex.y - radius), numVertices=3, radius=radius, color='r', zorder=9) self.one_fig.add_patch(support_patch) y = -node.vertex.z - 2 * radius self.one_fig.plot( [node.vertex.x - radius, node.vertex.x + radius], [y, y], color='r') elif direction == 1: # vertical roll # translate the support to the node support_patch = mpatches.Polygon(triangle, color='r', zorder=9) self.one_fig.add_patch(support_patch) y = node.vertex.y - radius self.one_fig.plot([ node.vertex.x + radius * 1.5, node.vertex.x + radius * 1.5 ], [y, y + 2 * radius], color='r') count += 1
def get_hexagon(self, correct_hex=False, edgecolor='magenta'): # the spacing should be ~0.5 arcsec not 0, and it should not be rotated by np.sqrt(3) / 2 if correct_hex: # each hex has a total diameter of 2.5 arcsec on the sky (only 2 of it is a fiber) diameter = 2.5 / 0.099 # the radius for mpl is from the center to each vertex, not center to side r = LUT[self.ifu_size] * diameter / 2 else: # this was me being wrong about all the hexagon params # these hexagons are about 0.7 times too small (2 * np.sqrt(3) / 5 to be exact) diameter = 2.0 / 0.099 r = LUT[self.ifu_size] * diameter * np.sqrt(3) / 4 c = self.center_in_pix() return patches.RegularPolygon(c, 6, r, fill=False, orientation=np.deg2rad(30), edgecolor=edgecolor, linewidth=0.8)
def __init__(self, xy, numVertices, radius, fill, fc, ec, lw, orientation, mplprops, figure): self.xy = xy self.numVertices = numVertices self.radius = radius self.fill = fill self.orientation = orientation self.lw = lw self.mplprops = mplprops self.figure = figure # Define the polygon polygon = patches.RegularPolygon(xy, numVertices, radius, fc=fc, ec=ec, fill=False, lw=lw, **self.mplprops) self.matplotlib_obj = polygon self.patch = self.figure.ax.add_patch(self.matplotlib_obj)
def addlatticeframe(lattice, M=[], geometry="square", save=False, limcolor=[0, 1], cmap='viridis'): global pc positions = [(lattice[idx]["xpos"], lattice[idx]["ypos"]) for idx in lattice] # positions of the cells Nsides = { "square": 4, "squarediag": 4, "hexagonal": 6 } # number of sides of each cell orientation = { "square": np.pi / 4, "squarediag": np.pi / 4, "hexagonal": 0 } # rotation of each cell patch_list = [] # this list will contain all the polygonal shapes for idx in lattice: patch_list.append( mpatches.RegularPolygon( # add a regular polygon xy=positions[idx], # at a certain position numVertices=Nsides[geometry], # with certain number of sides radius=0.5 / np.cos(np.pi / Nsides[geometry]), # with certain radius orientation=orientation[geometry], # and a certain rotation edgecolor=newblack # and borders of color )) pc = collections.PatchCollection( patch_list, match_original=True) # create a collection with the list pc.set( array=M, cmap=cmap) # set a color for each polygon based on the given array M pc.set_clim(limcolor) # set the min and max values for the color scale frame = axg.add_collection( pc ) # add the collection to the plotting axis and save the artist in frame movieframes.append((frame, )) print("frames: ", len(movieframes)) if save is not False: # if the argument save is set to a string e.g. "figure.pdf" plt.savefig(save) # it creates an output file return frame
def add_structure(ax, patches, position, spacegroup, energy): """ Add one polygon to the patches list :param ax: :param patches: :param position: :param spacegroup: :param energy: :return: """ polygon = mpatches.RegularPolygon(position, spacegroup2poly(spacegroup), 0.5, clip_on=True) patches.append(polygon) label(ax, position, spacegroup, energy)
def render_border(self, ax=None, **kwargs): """ Draws all 6 borders of a given Hexagon. fc will color the face.""" if ax is None: ax = plt.gca() rot_radians = pi / 6 if self.flat else 0 polygon = mpatches.RegularPolygon((self.x, self.y), numVertices=6, radius=self.size, orientation=rot_radians, **kwargs) ax.add_patch(polygon) return ax,
def drawCirc(ax, radius, centX, centY, angle_, theta2_, lineWidth=3, color_='black'): #========Line arc = patches.Arc([centX, centY], radius, radius, angle=angle_, theta1=0, theta2=theta2_, capstyle='round', linestyle='-', lw=lineWidth, color=color_) ax.add_patch(arc) #========Create the arrow head # endX=centX+(radius/2)*np.cos((theta2_+angle_)/180*np.pi) #Do trig to determine end position # endY=centY+(radius/2)*np.sin((theta2_+angle_)/180*np.pi) # ax.add_patch( #Create triangle as arrow head # patches.RegularPolygon( # (endX, endY), # (x,y) # 3, # number of vertices # radius/10, # radius # (angle_+theta2_)/180*np.pi, # orientation # color=color_ # ) # ) #========Create the arrow head begX = centX + (radius / 2) * np.cos( (angle_) / 180 * np.pi) #Do trig to determine end position begY = centY + (radius / 2) * np.sin((angle_) / 180 * np.pi) ax.add_patch( #Create triangle as arrow head patches.RegularPolygon( (begX, begY), # (x,y) 3, # number of vertices radius / 20, # radius (180 + angle_) / 180 * np.pi, # orientation color=color_)) ax.set_xlim([centX - radius, centY + radius]) and ax.set_ylim( [centY - radius, centY + radius])
def drawHex(self, ci, cj, fig, fclr): x = ci * np.cos(np.pi / 6) y = cj + (ci * np.sin(np.pi / 6)) center = np.asarray([2 * self.redge * x, 2 * self.redge * y]) vertices = [(center + z) for z in self.basis] eclr = [chr(keepzero(ord(vl) - 1)) for vl in fclr] eclr[0] = '#' axis = fig.gca() axis.add_patch( patches.RegularPolygon((center[0], center[1]), 6, self.radius, orientation=(np.pi / 2), fc=fclr, ec=''.join(eclr)))
def draw_hexagon(ax, center, color): # because the dimensions of the axes have been set in mm, # the dimensions of thie hexagon are given in mm as well. ax.add_patch( mpatches.RegularPolygon( xy=center, numVertices=6, # Due to rounding errors I think, it is better to make the hexagons # a little larger than the RADIUS parameter radius=RADIUS + 0.2, facecolor=color, edgecolor="none", orientation=0, fill=True, ))
def get_star_base(self): """ stars are based on n-vertex regular polygons Returns ------- numpy array an array of coordinates of vertices """ base = pt.RegularPolygon((0, 0), self.num_arms, self.radius) base_vertices = base.get_verts() fi = (360 / self.num_arms / 2 + self.star_rotation) * \ mt.pi / 180 # (internal_ang) * mt.pi / 180 return np.dot(rotation_matrix(fi), base_vertices.T).T + self.center
def animate(i): global clients, companies #clear figure at each iteration fig.clf() p = [] for k in districts: #https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html#matplotlib.patches.Circle package explanation #these are supposed to be the location (each district) p += [ patches.Circle((districts[k][0], districts[k][1]), radius=0.01, transform=fig.transFigure, figure=fig) ] for d in districts_connections: #https://matplotlib.org/api/_as_gen/matplotlib.patches.ConnectionPatch.html#matplotlib.patches.ConnectionPatch package explanation p += [ patches.ConnectionPatch(xyA=districts[d[0]], xyB=districts[d[1]], coordsA='figure fraction', coordsB='figure fraction', arrowstyle="-", transform=fig.transFigure, figure=fig) ] #moving between Setubal and Evora ####### this is just a demo (a point moving) TODO: implement the movement of the trucks ####### print(world_set.step(clients, companies)) #https://matplotlib.org/api/_as_gen/matplotlib.patches.RegularPolygon.html#matplotlib.patches.RegularPolygon package explanation for c in companies: trucks = c.getTrucksOnTheMove() for t in trucks: #print("Truck ", t.getID(), " is at ", t.getCoordinates(), " with destination ", t.getDestination()) p += [ patches.RegularPolygon(t.getCoordinates(), 4, radius=0.01, color='r', transform=fig.transFigure, figure=fig) ] #Add the objects updated to the figure fig.patches.extend(p) return fig
def plot_firstmoves(historyfile, hexgridfile, plotfile, **kwargs): _, _, coords = extract_history(historyfile, return_coords=True) coords = coords[:P.firstmoves_count] dcoords = dict() for i, v in enumerate(coords): if tuple(v) in dcoords.keys(): dcoords[tuple(v)].append(i) else: dcoords[tuple(v)] = [ i, ] fig = plt.figure(figsize=(8, 8)) ax = fig.gca() x, y, z, u, v, w = extract_xyzuvw(hexgridfile) colorsuv = np.arctan2(u, v) # phi = [-pi, pi] colorsuv = (colorsuv + np.pi) / (2 * np.pi) # [0, 1] patches = list() for i in range(x.shape[0]): patches.append(mpatches.RegularPolygon((x[i], y[i]), 6, 0.58)) collection_spins = PatchCollection(patches, facecolors=plt.get_cmap( P.phi_colormap)(colorsuv), alpha=0.3) ax.add_collection(collection_spins) for k in dcoords: xa, ya = tri2cart(k) s = ', '.join(map(str, [x + 1 for x in dcoords[k]])) ax.scatter(xa, ya, color='k') ax.annotate(s, (xa, ya), (xa, ya + 0.5), ha='center') xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max() dx, dy = xmax - xmin, ymax - ymin ax.set_xlim(xmin - dx / 25, xmax + dx / 25) ax.set_ylim(ymin - dy / 25, ymax + dy / 25) # ax.set_title('Spin direction', ha='right', fontsize=20) ax.set_aspect('equal') ax.set_ylabel('Y', rotation=0, ha='right', fontsize=20) ax.set_xlabel('X', fontsize=20) fig.savefig(plotfile, format=P.plot_format, bbox_inches='tight') plt.close()
def plot_rolled_support(self, max_val): """ :param max_val: max scale of the plot """ radius = 0.03 * max_val count = 0 for node in self.system.supports_roll: direction = self.system.supports_roll_direction[count] if direction == 2: # horizontal roll support_patch = mpatches.RegularPolygon( (node.point.x, -node.point.z - radius), numVertices=3, radius=radius, color='r', zorder=9) self.ax.add_patch(support_patch) y = -node.point.z - 2 * radius self.ax.plot([node.point.x - radius, node.point.x + radius], [y, y], color='r') elif direction == 1: # vertical roll center = 0 x1 = center + math.cos( math.pi) * radius + node.point.x + radius z1 = center + math.sin(math.pi) * radius - node.point.z x2 = center + math.cos( math.radians(90)) * radius + node.point.x + radius z2 = center + math.sin( math.radians(90)) * radius - node.point.z x3 = center + math.cos( math.radians(270)) * radius + node.point.x + radius z3 = center + math.sin( math.radians(270)) * radius - node.point.z triangle = np.array([[x1, z1], [x2, z2], [x3, z3]]) # translate the support to the node support_patch = mpatches.Polygon(triangle, color='r', zorder=9) self.ax.add_patch(support_patch) y = -node.point.z - radius self.ax.plot( [node.point.x + radius * 1.5, node.point.x + radius * 1.5], [y, y + 2 * radius], color='r') count += 1
def createNorthPointer(self): '''Creates the north pointer relative to current heading.''' self.headingNorthTri = patches.RegularPolygon((0.0, 0.80), 3, 0.05, color='k', zorder=4) self.axes.add_patch(self.headingNorthTri) self.headingNorthText = self.axes.text(0.0, 0.675, 'N', color='k', size=self.fontSize, horizontalalignment='center', verticalalignment='center', zorder=4)
def __rotating_spring_support_patch(self, max_val): """ :param max_val: max scale of the plot """ radius = PATCH_SIZE * max_val for node, _ in self.system.supports_spring_y: r = np.arange(0, radius, 0.001) theta = 25 * np.pi * r / (0.2 * max_val) x = np.cos(theta) * r + node.vertex.x y = np.sin(theta) * r - radius + node.vertex.y self.one_fig.plot(x, y, color='r', zorder=9) # Triangle support_patch = mpatches.RegularPolygon((node.vertex.x, node.vertex.y - radius * 3), numVertices=3, radius=radius * 0.9, color='r', zorder=9) self.one_fig.add_patch(support_patch)
def plot_agents_ij(self): worldstate = self.worldstate for i, a in enumerate(worldstate.get_agents()): xy = np.array(worldstate.get_xystates()[i]) ij = self.worldstate.map.xy_to_ij([xy])[0] GrYlRd = matplotlib.colors.LinearSegmentedColormap.from_list( "", ["tomato", "yellow", "springgreen"]) c = GrYlRd(worldstate.get_innerstates()[i].permissivity) r = a.radius / self.worldstate.map.resolution() if a.type() == agents.Robot: circle = patches.RegularPolygon((ij[0], ij[1]), 6, r, color=c) plt.gcf().gca().add_artist(circle) # marker = "^" # plt.scatter(ij[:1], ij[1:], marker=marker, c=[c]) else: circle = plt.Circle((ij[0], ij[1]), r, color=c) plt.gcf().gca().add_artist(circle)
def fig_gen(shape): if shape == "circle": #to generate a circle" ret = mpatches.Circle(grid[1], 0.1, ec="none") #print(ret) elif shape == "rectangle": #to generate a rectangle ret = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none") #print(ret) elif shape == "ellipse": #to generate an ellipse ret = mpatches.Ellipse(grid[1], 0.2, 0.1) #print(ret) elif shape == "polygon": #to generate a polygon ret = mpatches.RegularPolygon(grid[1], 5, 0.1) #print(ret) return ret
def flip_b_inverse(self, i): for patch in self.ax.patches: patch.set_visible(False) i = 10 - i if i < 0: i = 0 aflip = np.array([[-4 + (i * 0.4), -4 + (i * 0.8)], [0 + (i * -(0.4)), 4 + (i * -(0.8))], [4, -4]]) self.equilateral = patches.Polygon(xy=aflip, color='#4286f4') self.ax.add_patch(self.equilateral) if i == 0: self.marker1 = patches.RegularPolygon(xy=(-2.8, -3.2), numVertices=20, radius=0.65, color='#fff83a', alpha=0.7) self.marker2 = patches.RegularPolygon(xy=(0, 2.5), numVertices=20, radius=0.65, color='#ff1e40', alpha=0.7) self.marker3 = patches.RegularPolygon(xy=(2.8, -3.2), numVertices=20, radius=0.65, color='#59ff77', alpha=0.7) self.ax.add_patch(self.marker1) self.ax.add_patch(self.marker2) self.ax.add_patch(self.marker3) if i == 10: self.marker1 = patches.RegularPolygon(xy=(-2.8, -3.2), numVertices=20, radius=0.65, color='#ff1e40', alpha=0.7) self.marker2 = patches.RegularPolygon(xy=(0, 2.5), numVertices=20, radius=0.65, color='#fff83a', alpha=0.7) self.marker3 = patches.RegularPolygon(xy=(2.8, -3.2), numVertices=20, radius=0.65, color='#59ff77', alpha=0.7) self.ax.add_patch(self.marker1) self.ax.add_patch(self.marker2) self.ax.add_patch(self.marker3) return self.ax,
def _set_interactive_landmarks(self, xloc, yloc, status, belief, index): if status != InteractiveLandmarkStatus.CLEARED: if status == InteractiveLandmarkStatus.POSITIVE: color = 'darkgreen' elif status == InteractiveLandmarkStatus.NEGATIVE: color = 'darkred' adv = patches.RegularPolygon((xloc + 0.5, yloc + 0.5), 7, 0.35, linewidth=1, edgecolor=color, facecolor=color) props = dict(boxstyle='round', facecolor='yellow', alpha=1) propsid = dict(boxstyle='round', facecolor='white', alpha=0.7) text = "?" if belief == InteractiveLandmarkBelief.QUESTIONMARK else "!" self._ax.add_patch(adv) txt = self._ax.text(xloc + 0.6, yloc + 0.6, text, fontsize=10, verticalalignment='top', bbox=props) self._tmp_objects.append(txt) txt = self._ax.text(xloc + 0.3, yloc + 0.3, str(index+1), fontsize=10, verticalalignment='top', bbox=propsid) self._tmp_objects.append(txt) self._tmp_objects.append(adv)
def plot_single_lattice(coord_x, coord_y, face_color, edge_color, min_diam, plotting_gap, rotate_deg, h_ax=None): """ Adds a single lattice to the axes canvas. Multiple calls can be made to overlay few lattices. :return: """ if face_color is None: face_color = (1, 1, 1, 0) # Make the face transparent if edge_color is None: edge_color = 'k' if h_ax is None: h_fig = plt.figure(figsize=(5, 5)) h_ax = h_fig.add_axes([0.05, 0.05, 0.9, 0.9]) patches = [] for curr_x, curr_y in zip(coord_x, coord_y): polygon = mpatches.RegularPolygon( (curr_x, curr_y), numVertices=6, radius=min_diam / np.sqrt(3) * (1 - plotting_gap), orientation=np.deg2rad(-rotate_deg)) patches.append(polygon) collection = PatchCollection(patches, edgecolor=edge_color, facecolor=face_color) h_ax.add_collection(collection) h_ax.set_aspect('equal') h_ax.axis([ coord_x.min() - 2 * min_diam, coord_x.max() + 2 * min_diam, coord_y.min() - 2 * min_diam, coord_y.max() + 2 * min_diam ]) # plt.plot(0, 0, 'r.', markersize=5) # Add red point at the origin return h_ax
def createWPPointer(self): '''Creates the waypoint pointer relative to current heading.''' self.headingWPTri = patches.RegularPolygon((0.0, 0.55), 3, 0.05, facecolor='lime', zorder=4, ec='k') self.axes.add_patch(self.headingWPTri) self.headingWPText = self.axes.text(0.0, 0.45, '1', color='lime', size=self.fontSize, horizontalalignment='center', verticalalignment='center', zorder=4) self.headingWPText.set_path_effects( [PathEffects.withStroke(linewidth=1, foreground='k')])
def plot_single_lattice_custom_colors(coord_x, coord_y, face_color, edge_color, min_diam, plotting_gap, rotate_deg, h_ax=None): """ Plot hexagonal lattice where every hexagon is colored by an individual color. All inputs are similar to the plot_single_lattice() except: :param face_color: numpy array, Nx3 or Nx4 - Color list of length |coord_x| for each hexagon face. Each row is a RGB or RGBA values, e.g. [0.3 0.3 0.3 1] :param edge_color: numpy array, Nx3 or Nx4 - Color list of length |coord_x| for each hexagon edge. Each row is a RGB or RGBA values, e.g. [0.3 0.3 0.3 1] :return: """ if h_ax is None: h_fig = plt.figure(figsize=(5, 5)) h_ax = h_fig.add_axes([0.05, 0.05, 0.9, 0.9]) patches = [] for i, (curr_x, curr_y) in enumerate(zip(coord_x, coord_y)): polygon = mpatches.RegularPolygon( (curr_x, curr_y), numVertices=6, radius=min_diam / np.sqrt(3) * (1 - plotting_gap), orientation=np.deg2rad(-rotate_deg), edgecolor=edge_color[i], facecolor=face_color[i]) h_ax.add_artist(polygon) h_ax.set_aspect('equal') h_ax.axis([ coord_x.min() - 2 * min_diam, coord_x.max() + 2 * min_diam, coord_y.min() - 2 * min_diam, coord_y.max() + 2 * min_diam ]) # plt.plot(0, 0, 'r.', markersize=5) # Add red point at the origin return h_ax
def main(): xy1 = np.array([0.2, 0.2]) xy2 = np.array([0.2, 0.8]) xy3 = np.array([0.8, 0.2]) xy4 = np.array([0.8, 0.8]) ax = plt.subplot() """ 圆 """ circle = patch.Circle(xy1, 0.1) ax.add_patch(circle) """ 长方形 """ rect = patch.Rectangle(xy2, 0.2, 0.1, color='r') ax.add_patch(rect) """ 多边形 """ polygon = patch.RegularPolygon(xy3, 6, 0.1, color='g') ax.add_patch(polygon) """ 椭圆 """ ellipse = patch.Ellipse(xy4, 0.4, 0.2, color='c') ax.add_patch(ellipse) ax.axis('equal') plt.show()
def make_mask(shape, dpi): mask_fig = plt.figure(figsize=(6, 6), facecolor='w', dpi=dpi) mask_ax = mask_fig.add_subplot(111) xy_center = (0.5, 0.5) if (shape == 'circle' or shape == 'c'): mask_ax.add_patch(patches.Circle(xy_center, 0.5)) elif (shape == 'ellipse' or shape == 'e'): mask_ax.add_patch(patches.Ellipse(xy_center, 1, 0.75)) elif (shape == 'rectangle' or shape == 'r'): mask_ax.add_patch(patches.Rectangle((0, 0.15), 1, 0.7)) elif (shape == 'square' or shape == 's'): mask_ax.add_patch(patches.Rectangle((0, 0), 1, 1)) else: shape = int(shape) mask_ax.add_patch(patches.RegularPolygon(xy_center, shape, 0.5)) mask_ax.axis('off') mask_fig.savefig('mask.png') mask = np.array(Image.open('mask.png')) plt.close() return mask
def PlotPix(filename, name = None ): print filename data_pix = numpy.genfromtxt(filename, usecols=(4, 5, 6), skip_header=4, max_rows=1296, unpack=True) #data_patch = numpy.genfromtxt(filename, usecols=(4, 5, 6, 7), skip_header=3907, max_rows=433, unpack=True) ax = fig.add_subplot(111, aspect='equal', title = '') ax.set_xlim([min(data_pix[1, :]) - 25, max(data_pix[1, :]) + 25]) ax.set_ylim([min(data_pix[2, :]) - 25, max(data_pix[2, :]) + 25]) for p in [patches.RegularPolygon((data_pix[1, i], data_pix[2, i]), 6, 13.4, fill=False, edgecolor="green") for i in range(len(data_pix[0, :])) ]: ax.add_patch(p) if args["--identif"] : for i in range(len(data_pix[0, :])): plt.text(data_pix[1, i], data_pix[2, i], '%d' % data_pix[0, i], horizontalalignment='center', verticalalignment='center', fontsize=5)