def get_state_maps(list): counter = 0 for x in list: ax = plt.gca() seg = map.states[state_names.index(x)] poly = Polygon(seg, facecolor='red', edgecolor='red') ax.add_patch(poly) savefig('images/map/map' + str(counter) + '.png', bbox_inches='tight') poly.set_facecolor('None') poly.set_edgecolor('None') counter += 1
def animate_polygons(self, frame): point = self.path[frame] polygon = Polygon(self.get_polygon_points(point), True) if point not in [self.maze.start, self.maze.exit]: if point in self.path[:frame]: #backtracking polygon.set_facecolor(self.polygon_backtracking_color) polygon.set_edgecolor(self.polygon_backtracking_edge_color) self.ax.add_patch(polygon) else: polygon.set_facecolor(self.polygon_face_color) polygon.set_edgecolor(self.polygon_edge_color) self.ax.add_patch(polygon) if point == self.maze.exit: polygon.set_facecolor(self.exit_color) polygon.set_alpha(1) self.ax.add_patch(polygon) return []
class Roi(object): def __init__(self, xy, name, colour, linewidth=None): ''' A ROI is defined by its vertices (xy coords), a name, and a colour. Input: xy Coordinates of the ROI as a numpy array of shape (2, N). name Name of the ROI, string. colour Colour definition in any format acceptable to matplotlib, ie named (e.g. 'white') or RGBA format (e,g. (1.0, 1.0, 1.0, 1.0)). ''' super(Roi, self).__init__() self.polygon = Polygon(xy, lw=linewidth) self.polygon.set_facecolor('none') self.name = name self.set_colour(colour) def set_colour(self, colour): self.polygon.set_edgecolor(colour) def get_colour(self): return self.polygon.get_edgecolor() def set_name(self, name): self.name = name def get_name(self): return self.name def set_xy(self): return self.polygon.set_xy() def get_xy(self): return self.polygon.get_xy() def get_polygon(self): return self.polygon
def draw_agents(agents_number: int, polytopes: list, space_size: float, draw_circles: bool = True) -> None: """ Draws the agents' positions as circles. Used to display simulation results. Parameters ---------- agents_number : int total number of agents in the mission plane polytopes : list shape - (agents_number, 2) positions of the agents space_size : float dimension of the mission plane draw_circles : bool true if the agent circles are to be drawn, false otherwise Returns ------- None """ ax = plt.gca() plt.axis([0, space_size, 0, space_size]) for agent_index in range(agents_number): polytope = polytopes[agent_index] position = polytope.get_center_position() position_x = position[0] position_y = position[1] agent_vertices = polytope.get_vertices() polygon = Polygon(agent_vertices) if draw_circles: circle = plt.Circle((position_x, position_y), 2, fill=False) ax.add_artist(circle) else: polygon.set_edgecolor("black") ax.add_artist(polygon)
def plot_fits_map(data, header, stretch='auto', exponent=2, scaleFrac=0.9, cmapName='gist_heat', zMin=None, zMax=None, annEllipseLst=[], annPolyLst=[], bunit=None, lw=1.0, interpolation='Nearest', fig=None, dpi=100, doColbar=True): """ Plot a colourscale image of a FITS map. annEllipseLst is a list of lists: annEllipseLst[0][i] = x_deg annEllipseLst[1][i] = y_deg annEllipseLst[2][i] = minor_deg annEllipseLst[3][i] = major_deg annEllipseLst[4][i] = pa_deg annEllipseLst[5][i] = colour ... optional, default to 'g' annPolyLst is also a list of lists: annPolyLst[0][i] = list of polygon coords = [[x1,y1], [x2, y2] ...] annPolyLst[1][i] = colour of polygon e.g., 'w' """ # Strip unused dimensions from the array data, header = strip_fits_dims(data, header, 2, 5) # Parse the WCS information w = mkWCSDict(header) wcs = pw.WCS(w['header2D']) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX = int(s[-1] / 2.0 + s[-1] * scaleFrac / 2.0 + 1.0) boxMinX = int(s[-1] / 2.0 - s[-1] * scaleFrac / 2.0 + 1.0) boxMaxY = int(s[-2] / 2.0 + s[-2] * scaleFrac / 2.0 + 1.0) boxMinY = int(s[-2] / 2.0 - s[-2] * scaleFrac / 2.0 + 1.0) dataSample = data[boxMinY:boxMaxY, boxMinX:boxMaxX] measures = calc_stats(dataSample) sigma = abs(measures['max'] / measures['madfm']) if stretch == 'auto': if sigma <= 20: vMin = measures['madfm'] * (-1.5) vMax = measures['madfm'] * 10.0 stretch = 'linear' elif sigma > 20: vMin = measures['madfm'] * (-3.0) vMax = measures['madfm'] * 40.0 stretch = 'linear' elif sigma > 500: vMin = measures['madfm'] * (-7.0) vMax = measures['madfm'] * 200.0 stretch = 'sqrt' if not zMax is None: vMax = max(zMax, measures['max']) if not zMax is None: vMin = zMin # Set the colourscale using an normalizer object normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) # Setup the figure if fig is None: fig = plt.figure(facecolor='w', figsize=(9.5, 8)) ax = fig.add_axes([0.1, 0.08, 0.9, 0.87]) if w['coord_type'] == 'EQU': ax.set_xlabel('Right Ascension') ax.set_ylabel('Declination') elif w['coord_type'] == 'GAL': ax.set_xlabel('Galactic Longitude (deg)') ax.set_ylabel('Galactic Latitude (deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosY = m.cos(m.radians(w['ycent'])) aspect = abs(w['ydelt'] / (w['xdelt'] * cosY)) # Set the format of the major tick mark and labels if w['coord_type'] == 'EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) # Set the location of the the major tick marks #xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) #xmultiple = m.ceil(xrangeArcmin/3.0)/(60.0*f) #yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 #ymultiple = m.ceil(yrangeArcmin/3.0)/60.0 #majorLocatorX = MultipleLocator(xmultiple) #ax.xaxis.set_major_locator(majorLocatorX) #majorLocatorY = MultipleLocator(ymultiple) #ax.yaxis.set_major_locator(majorLocatorY) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(5)) # Print the image to the axis im = ax.imshow(data, interpolation=interpolation, origin='lower', aspect=aspect, extent=[w['xmax'], w['xmin'], w['ymin'], w['ymax']], cmap=plt.get_cmap(cmapName), norm=normalizer) # Add the colorbar if doColbar: cbar = fig.colorbar(im, pad=0.0) if 'BUNIT' in header: cbar.set_label(header['BUNIT']) else: cbar.set_label('Unknown') if not bunit is None: cbar.set_label(bunit) # Format the colourbar labels - TODO # Set white ticks ax.tick_params(pad=5) for line in ax.xaxis.get_ticklines() + ax.get_yticklines(): line.set_markeredgewidth(1) line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcXLst = np.array(annEllipseLst[0]) srcYLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcXLst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcXLst) else: srcEColLst = ['g'] * len(srcXLst) for i in range(len(srcXLst)): try: el = Ellipse((srcXLst[i], srcYLst[i]), srcMinLst[i], srcMajLst[i], angle=180.0 - srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) except Exception: pass # Create the polygon source annotations if len(annPolyLst) > 0: annPolyCoordLst = annPolyLst[0] if len(annPolyLst) > 1: if type(annPolyLst[1]) is str: annPolyColorLst = [annPolyLst[1]] * len(annPolyCoordLst) elif type(annPolyLst[1]) is list: annPolyColorLst = annPolyLst[1] else: annPolyColorLst = ['g'] * len(annPolyCoordLst) else: annPolyColorLst = ['g'] * len(annPolyCoordLst) for i in range(len(annPolyCoordLst)): cpoly = Polygon(annPolyCoordLst[i], animated=False, linewidth=lw) cpoly.set_edgecolor(annPolyColorLst[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) return fig
titleax.axis("off") m = Basemap(projection='eck4', lon_0=160, resolution='c', ax=ax) m.drawcoastlines(linewidth=0, color="#FFFFFF") m.drawmapboundary(color="aqua") m.fillcontinents(color='#cccccc', lake_color='#FFFFFF') # Read shapefile m.readshapefile("data/ne_10m_admin_0_countries/ne_10m_admin_0_countries", "units", drawbounds=False) patches = [] for info, shape in zip(m.units_info, m.units): poly = Polygon(np.array(shape), True) poly.set_facecolor('none') poly.set_linewidth(0) poly.set_edgecolor("#000000") poly.set_zorder(1) poly = ax.add_patch(poly) patches.append(poly) x1, y1 = m(coords["lng"].values, coords["lat"].values) _c = [scalarMap.to_rgba(groups.index(i)) for i in groups] p = m.scatter(x1, y1, marker="o", alpha=1, color=_c, zorder=2, sizes=[0] * coords.shape[0]) lwidths = list(np.logspace(np.log(1), np.log(5), 300, base=np.e))
def plot_fits_map(data, header, stretch='auto', exponent=2, scaleFrac=0.9, cmapName='gist_heat', zMin=None, zMax=None, annEllipseLst=[], annPolyLst=[], bunit=None, lw=1.0, interpolation='Nearest', fig=None, dpi=100, doColbar=True): """ Plot a colourscale image of a FITS map. annEllipseLst is a list of lists: annEllipseLst[0][i] = x_deg annEllipseLst[1][i] = y_deg annEllipseLst[2][i] = minor_deg annEllipseLst[3][i] = major_deg annEllipseLst[4][i] = pa_deg annEllipseLst[5][i] = colour ... optional, default to 'g' annPolyLst is also a list of lists: annPolyLst[0][i] = list of polygon coords = [[x1,y1], [x2, y2] ...] annPolyLst[1][i] = colour of polygon e.g., 'w' """ # Strip unused dimensions from the array data, header = strip_fits_dims(data, header, 2, 5) # Parse the WCS information w = mkWCSDict(header) wcs = pw.WCS(w['header2D']) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX = int( s[-1]/2.0 + s[-1] * scaleFrac/2.0 + 1.0 ) boxMinX = int( s[-1]/2.0 - s[-1] * scaleFrac/2.0 + 1.0 ) boxMaxY = int( s[-2]/2.0 + s[-2] * scaleFrac/2.0 + 1.0 ) boxMinY = int( s[-2]/2.0 - s[-2] * scaleFrac/2.0 + 1.0 ) dataSample = data[boxMinY:boxMaxY, boxMinX:boxMaxX] measures = calc_stats(dataSample) sigma = abs(measures['max'] / measures['madfm']) if stretch=='auto': if sigma <= 20: vMin = measures['madfm'] * (-1.5) vMax = measures['madfm'] * 10.0 stretch='linear' elif sigma > 20: vMin = measures['madfm'] * (-3.0) vMax = measures['madfm'] * 40.0 stretch='linear' elif sigma > 500: vMin = measures['madfm'] * (-7.0) vMax = measures['madfm'] * 200.0 stretch='sqrt' if not zMax is None: vMax = max(zMax, measures['max']) if not zMax is None: vMin = zMin # Set the colourscale using an normalizer object normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) # Setup the figure if fig is None: fig = plt.figure(figsize=(9.5, 8)) ax = fig.add_axes([0.1, 0.08, 0.9, 0.87]) if w['coord_type']=='EQU': ax.set_xlabel('Right Ascension') ax.set_ylabel('Declination') elif w['coord_type']=='GAL': ax.set_xlabel('Galactic Longitude (deg)') ax.set_ylabel('Galactic Latitude (deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosY = m.cos( m.radians(w['ycent']) ) aspect = abs( w['ydelt'] / (w['xdelt'] * cosY)) # Set the format of the major tick mark and labels if w['coord_type']=='EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) # Set the location of the the major tick marks #xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) #xmultiple = m.ceil(xrangeArcmin/3.0)/(60.0*f) #yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 #ymultiple = m.ceil(yrangeArcmin/3.0)/60.0 #majorLocatorX = MultipleLocator(xmultiple) #ax.xaxis.set_major_locator(majorLocatorX) #majorLocatorY = MultipleLocator(ymultiple) #ax.yaxis.set_major_locator(majorLocatorY) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(5)) # Print the image to the axis im = ax.imshow(data, interpolation=interpolation, origin='lower', aspect=aspect, extent=[w['xmax'], w['xmin'], w['ymin'], w['ymax']], cmap=plt.get_cmap(cmapName), norm=normalizer) # Add the colorbar if doColbar: cbar = fig.colorbar(im, pad=0.0) if 'BUNIT' in header: cbar.set_label(header['BUNIT']) else: cbar.set_label('Unknown') if not bunit is None: cbar.set_label(bunit) # Format the colourbar labels - TODO # Set white ticks ax.tick_params(pad=5) for line in ax.xaxis.get_ticklines() + ax.get_yticklines(): line.set_markeredgewidth(1) line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcXLst = np.array(annEllipseLst[0]) srcYLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcXLst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcXLst) else: srcEColLst = ['g'] * len(srcXLst) for i in range(len(srcXLst)): try: el = Ellipse((srcXLst[i], srcYLst[i]), srcMinLst[i], srcMajLst[i], angle=180.0-srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) except Exception: pass # Create the polygon source annotations if len(annPolyLst) > 0: annPolyCoordLst = annPolyLst[0] if len(annPolyLst) > 1: if type(annPolyLst[1]) is str: annPolyColorLst = [annPolyLst[1]] * len(annPolyCoordLst) elif type(annPolyLst[1]) is list: annPolyColorLst = annPolyLst[1] else: annPolyColorLst = ['g'] * len(annPolyCoordLst) else: annPolyColorLst = ['g'] * len(annPolyCoordLst) for i in range(len(annPolyCoordLst)): cpoly = Polygon(annPolyCoordLst[i], animated=False, linewidth=lw) cpoly.set_edgecolor(annPolyColorLst[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) return fig
def plotfits1(data,header,outFile,scaleFrac=0.9,stretch='linear', exponent=2, cmapName='gist_heat',zmin=None,zmax=None, annEllipseLst=[], annPolyLst=[], annPolyColor='g', lw=1.0, dpi=100, interpolation='Nearest'): """Make a full-size and a thumbnail jpeg image of the file""" outDir,outFileName = os.path.split(outFile) outFileRoot,outExt = os.path.splitext(outFileName) # Strip unused dimensions from the array data,header = strip_fits_dims(data,header,2, 4) # Parse the WCS information wcs = pw.WCS(header) w = mkWCSDict(header) # Calculate the image vmin and vmax by measuring the range in the inner # 'scale_frac' of the image s = data.shape boxMaxX=int((s[-1]/2.0)+(s[-1]*scaleFrac/2.0)+1.0) boxMinX=int((s[-1]/2.0)-(s[-1]*scaleFrac/2.0)+1.0) boxMaxY=int((s[-2]/2.0)+(s[-2]*scaleFrac/2.0)+1.0) boxMinY=int((s[-2]/2.0)-(s[-2]*scaleFrac/2.0)+1.0) vMin = np.nanmin(data[boxMinY:boxMaxY,boxMinX:boxMaxX]) vMax = np.nanmax(data[boxMinY:boxMaxY,boxMinX:boxMaxX]) if zmax: vMax = zmax if zmin: vMin = zmin normalizer = APLpyNormalize(stretch=stretch, exponent=exponent, vmin=vMin, vmax=vMax) #-------------------------------------------------------------------------# # Setup the figure fig = plt.figure(figsize=(9.5,8)) ax = fig.add_subplot(111, position=[0.1,0.08,0.9,0.87]) # Single pane if w['coord_type']=='EQU': ax.set_xlabel('RA (J2000)') ax.set_ylabel('Dec (J2000)') elif w['coord_type']=='GAL': ax.set_xlabel('Galactic Longitude (Deg)') ax.set_ylabel('Galactic Latitude (Deg)') else: ax.set_xlabel('Unknown') ax.set_ylabel('Unknown') cosy = m.cos(m.radians(w['ycent'])) aspect = abs(w['ydelt']/(w['xdelt']*cosy)) # Set the format of the tick mark labels if w['coord_type']=='EQU': f = 15.0 majorFormatterX = FuncFormatter(label_format_hms) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_dms) minorFormattery = None else: f = 1.0 majorFormatterX = FuncFormatter(label_format_deg) minorFormatterX = None majorFormatterY = FuncFormatter(label_format_deg) minorFormattery = None ax.xaxis.set_major_formatter(majorFormatterX) ax.yaxis.set_major_formatter(majorFormatterY) xrangeArcmin = abs(w['xmax']-w['xmin'])*(60.0*f) xmultiple = m.ceil(xrangeArcmin/4.0)/(60.0*f) yrangeArcmin = abs(w['ymax']-w['ymin'])*60.0 ymultiple = m.ceil(yrangeArcmin/4.0)/60.0 majorLocatorX = MultipleLocator(xmultiple) ax.xaxis.set_major_locator(majorLocatorX) majorLocatorY = MultipleLocator(ymultiple) ax.yaxis.set_major_locator(majorLocatorY) # Print the image to the figure im = ax.imshow(data,interpolation=interpolation,origin='lower', aspect=aspect, extent=[w['xmax'],w['xmin'],w['ymin'],w['ymax']], cmap=plt.get_cmap(cmapName),norm=normalizer) # Add the colorbar cbar = fig.colorbar(im ,pad=0.0) cbar.set_label('mJy/beam') # Set white ticks for line in ax.xaxis.get_ticklines(): line.set_color('w') for line in ax.yaxis.get_ticklines(): line.set_color('w') # Create the ellipse source annotations if len(annEllipseLst) > 0: if len(annEllipseLst) >= 5: srcRALst = np.array(annEllipseLst[0]) srcDecLst = np.array(annEllipseLst[1]) srcMinLst = np.array(annEllipseLst[2]) srcMajLst = np.array(annEllipseLst[3]) srcPALst = np.array(annEllipseLst[4]) if len(annEllipseLst) >= 6: if type(annEllipseLst[5]) is str: srcEColLst = [annEllipseLst[5]] * len(srcRALst) elif type(annEllipseLst[5]) is list: srcEColLst = annEllipseLst[5] else: rcEColLst = ['g'] * len(srcRALst) else: srcEColLst = ['g'] * len(srcRALst) for i in range(len(srcRALst)): el = Ellipse((srcRALst[i],srcDecLst[i]), srcMinLst[i], srcMajLst[i], angle=180-srcPALst[i], edgecolor=srcEColLst[i], linewidth=lw, facecolor='none') ax.add_artist(el) # Create the polygon source annotations if len(annPolyLst) > 0: if type(annPolyColor) is str: annPolyColor = [annPolyColor] * len(annPolyLst) elif type(annPolyColor) is list: pass else: annPolyColor =['g'] * len(annPolyLst) for i in range(len(annPolyLst)): cpoly = Polygon(annPolyLst[i], animated=False,linewidth=lw) cpoly.set_edgecolor(annPolyColor[i]) cpoly.set_facecolor('none') ax.add_patch(cpoly) # Save to an image file (full-size & thumbnail images) fig.savefig(outFile, dpi=dpi) plt.close()
# csvfile = csv.reader(infile) # for line in csvfile: # lon = (float(line[0]) + float(line[2]))/2 + float(line[5]) # lat = (float(line[1]) + float(line[3]))/2 + float(line[6]) # x, y = m(lon, lat) # name = line[4].replace('\\n', '\n') # plt.text(x, y, name, horizontalalignment='center', verticalalignment='center', fontsize=int(line[7])) for lakepoly in m.lakepolygons: lp = Polygon(lakepoly.boundary, zorder=2) lp.set_facecolor('0.8') lp.set_edgecolor('0.8') lp.set_linewidth(0.1) ax.add_patch(lp) # xx, yy = m(-72.0, 26.0) # plt.text(xx, yy, u'Made by zhyuey', color='yellow') # plt.title('Map of contiguous United States', fontsize=24) # # plt.savefig('usa_state_75.png', dpi=75) # # plt.savefig('usa_state_75.png', dpi=75) # plt.savefig('usa_state_300.png', dpi=300) # # plt.savefig('usa_state_600.png', dpi=600) # m.drawcoastlines(linewidth=0.3)
def plot_planform(c_r, c_k, c_t, b_k, b, Lambda_le_1, Lambda_le_2, *args, **kwargs): fig = plt.subplots(figsize=(9, 9)) # optional arguments c_mac = kwargs.get('mac', None) X_le_mac = kwargs.get('X_le_mac', None) Y_mac = kwargs.get('Y_mac', None) X_ac = kwargs.get('X_ac', None) xLineWing = [0, b_k/2, b/2, b/2, b_k/2, 0] dy_k = (b_k/2)*math.tan(Lambda_le_1) dy = dy_k + (b/2 - b_k/2)*math.tan(Lambda_le_2) yLineWing = [ 0, dy_k, dy, dy + c_t, dy_k + c_k, c_r] # planform lineWing, = plt.plot(xLineWing, yLineWing, 'k-') plt.scatter(xLineWing, yLineWing, marker='o', s=40) # centerline centerLine, = plt.plot([0,0], [-0.2*c_r,2.1*c_r], 'b') centerLine.set_dashes([8, 4, 2, 4]) # c/4 line pC4r = [0, 0.25*c_r] pC4k = [b_k/2, dy_k + 0.25*c_k] pC4t = [b/2, dy + 0.25*c_t] quarterChordLine, = plt.plot([pC4r[0],pC4k[0],pC4t[0]], [pC4r[1],pC4k[1],pC4t[1]], 'k--') plt.scatter([pC4r[0],pC4k[0],pC4t[0]], [pC4r[1],pC4k[1],pC4t[1]], marker='o', s=40) if ('mac' in kwargs) and ('X_le_mac' in kwargs) and ('Y_mac' in kwargs): c_mac = kwargs['mac'] X_le_mac = kwargs['X_le_mac'] Y_mac = kwargs['Y_mac'] #print(mac) #print(X_le_mac) #print(Y_mac) lineMAC, = plt.plot([Y_mac, Y_mac], [X_le_mac, X_le_mac + c_mac], color="red", linewidth=2.5, linestyle="-") lineMAC.set_dashes([1000,1]) # HUUUUGE lineLEMAC, = plt.plot([0,b/2], [X_le_mac,X_le_mac], color="orange", linewidth=1.5, linestyle="-") lineLEMAC.set_dashes([10,2]) lineTEMAC, = plt.plot([0,b/2], [X_le_mac + c_mac, X_le_mac + c_mac], color="orange", linewidth=1.5, linestyle="-") lineTEMAC.set_dashes([10,2]) plt.scatter(Y_mac, X_le_mac, marker='o', s=40) ax = plt.gca() # gca stands for 'get current axis' ax.annotate( r'$(Y_{\bar{c}},X_{\mathrm{le},\bar{c}}) = ' +r'( {0:.3}'.format(Y_mac) + r'\,\mathrm{m}'+r',\,{0:.3}'.format(X_le_mac) + r'\,\mathrm{m} )$', xy=(Y_mac, X_le_mac), xycoords='data', xytext=(20, 30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # if ('X_le_r_eq' in kwargs) and ('c_r_eq' in kwargs): X_le_r_eq = kwargs['X_le_r_eq'] c_r_eq = kwargs['c_r_eq'] vertices = [(0, X_le_r_eq)] + [(b/2, dy)] + [(b/2, dy+c_t)] + [(0, X_le_r_eq + c_r_eq)] poly = Polygon(vertices, facecolor="yellow", alpha=0.5) poly.set_edgecolor("brown") poly.set_linewidth(2) ax0 = plt.gca() # gca stands for 'get current axis' ax0.add_patch(poly) if 'X_ac' in kwargs: X_ac = kwargs['X_ac'] #print(X_ac) plt.scatter(0, X_ac, marker='o', s=40) lineAC, = plt.plot([0,b/2], [X_ac,X_ac], color="brown", linewidth=3.5, linestyle="-") lineAC.set_dashes([10,2.5,3,2.5]) ax = plt.gca() # gca stands for 'get current axis' ax.annotate(r'$X_{\mathrm{ac,W}} = '+r'{0:.3}'.format(X_ac)+r'\,\mathrm{m} $', xy=(b/2, X_ac), xycoords='data', xytext=(20, 30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # plt.axis('equal') # xmajorLocator = MultipleLocator(2.0) # xmajorFormatter = FormatStrFormatter('%.1f') # xminorLocator = MultipleLocator(4) # ax = plt.gca() # gca stands for 'get current axis' # ax.xaxis.set_major_locator(xmajorLocator) # ax.xaxis.set_major_formatter(xmajorFormatter) # # for the minor ticks, use no labels; default NullFormatter # ax.xaxis.set_minor_locator(xminorLocator) plt.axis([-0.02*b/2, 1.1*b/2, -0.05*c_r, 1.1*(dy + c_t)]) plt.gca().invert_yaxis() plt.title('Wing planform', fontsize=16) plt.xlabel('$y$ (m)', fontsize=16) plt.ylabel('$X$ (m)', fontsize=16) # Moving spines ax = plt.gca() # gca stands for 'get current axis' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('outward',10)) # outward by 10 points ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',-0.07*b/2)) plt.show()
circle.set_edgecolor('crimson') circle.set_linewidth(3) circle.set_facecolor(None) patches = [circle] for i in range(nPolys): p = [1] + [0] * (n - 1) + [-z[i]] roots = np.roots(p) angles = np.sort([cmath.phase(root) for root in roots]) roots = np.cos(angles) + j * np.sin(angles) x = roots.real y = roots.imag coords = np.stack((x, y), axis=1) poly = Polygon(xy=coords, closed=True) poly.set_edgecolor('royalblue') poly.set_facecolor('lightsteelblue') poly.set_linewidth(1) patches.append(poly) fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) # Set bottom and left spines as x and y axes of coordinate system ax.spines['bottom'].set_position('zero') ax.spines['left'].set_position('zero') # Remove top and right spines ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # Create 'x' and 'y' labels placed at the end of the axes ax.set_xlabel('x', size=14, labelpad=-24, x=1.03)
def plot_elevation(lons, lats, elevation, cmap="Reds_r", levels=None, inset_bounds=None): """ Create a contour plot, usually for elevation data. Given longitudes, latitudes, and elevation data, create a filled contour of the data. The data should be regularly gridded. A colorbar for the plot is also created. Optionally, you can make an inset of a region of interest. Parameters ---------- lons : array An N-element array of longitudes of the data lats : array An M-element array of latitudes of the data elevation : array An NxM-element array of the elevation of the data. The first dimension corresponds to the lons , and the second dimension corresponds to the lats . cmap : str, optional A named colormap name from Matplotlib. Default is to use Reds_r. levels : array, optional The levels to be contoured. By default, 10 levels spanning the min/max of the elevation will be used. inset : boolean, optional If True, an inset plot is also created. inset_bounds: array, optional The inset_bounds is a 4 element array-like value (e.g., an array, list, or tuple) in the order of [lon_min, lon_max, lat_min, lat_max]. By default, None which means no inset_bounds has been set thus no inset will be created. Returns ------- SimpleNamespace Returned value has several keys, some of which are optionally included. :contour: Matplotlib QuadContourSet :colorbar: Matplotlib Colorbar class :inset_bounds: Matplotlib QuadContourSet (if inset_bounds is requested) :polygon: Matplotlib Polygon (if inset_bounds is requested) The polygon of the inset.:lines: A list of Matplotlib CollectionPatch-es (if inset_bounds is requested) Examples ------- >>> from scipy.stats import multivariate_normal >>> import numpy as np # Generate some lats and lons >>> lons = np.arange(100) >>> lats = np.arange(100) # Make these 2D "coordinate" arrays >>> lons2d, lats2d = np.meshgrid(lons, lats) # Fill in coordinates to find the 2D Gaussian PDF >>> coord = np.empty(lons2d.shape + (2,)) >>> coord[:, :, 0] = lons2d >>> coord[:, :, 1] = lats2d >>> mean = [1, -2] # coordinates of Gaussian peak >>> cov = [[5.0, 0], [0.0, 20.0]] # covariance array - width of peak # Generate the elevation data >>> rv = multivariate_normal(mean, cov) >>> data = rv.pdf(coord) >>> data = data/np.max(data)*400 # scale the data >>> elv_plot = plot_elevation(lons, lats, data) # Pick some new levels >>> elv_plot2 = plot_elevation(lons, lats, data, levels = np.arange(0, 300, 50)) """ import matplotlib.colors as mplcol from matplotlib.patches import Polygon, ConnectionPatch import numpy as np all_plots = SimpleNamespace() # all plots are added to this to be returned ##Pick levels for contour: if levels is None: levels = np.linspace(np.nanmin(elevation), np.nanmax(elevation), 10) # Build the color map, based on a Matplotlib colormap. # Get two extra colors for extending colors to the min _and_ max colors = plt.cm.get_cmap(cmap)(np.linspace(0, 1, levels.size + 2)) # The new color map for the levels cmap_mod = mplcol.ListedColormap(colors[1:-1, :]) # Set the min/max (under/over) for the extended colorbar cmap_mod.set_over(colors[-1, :]) cmap_mod.set_under(colors[0, :]) # Pack these up into a dictionary for the contour plot, # and add extending contours to min and max contourProps = {'levels': levels, 'cmap': cmap_mod, 'extend': 'both'} ##Plot the elevation contour ##**contourProps: keyword extension fig, ax = plt.subplots(figsize=(8, 6), dpi=100) c_big = ax.contourf(lons, lats, elevation, **contourProps) all_plots.contour = c_big ##Make the colorbar cb = c_big.ax.figure.colorbar(c_big) all_plots.colorbar = cb ##Make an inset if inset_bounds is not None: print("You have requested an inset: [lon_min, lon_max]=", inset_bounds[:2], " [lat_min, lat_max]=", inset_bounds[-2:]) # Set the corners of the polygon #lat_poly = [34.65, 34.85] lat_poly = inset_bounds[-2:] #lon_poly = [-86.65, -86.45] lon_poly = inset_bounds[:2] # Define the vertices for the polygon lat_vert = [lat_poly[0], lat_poly[1], lat_poly[1], lat_poly[0]] lon_vert = [lon_poly[0], lon_poly[0], lon_poly[1], lon_poly[1]] lon_lat = np.column_stack((lon_vert, lat_vert)) # Draw the polygon poly = Polygon(lon_lat) _null = c_big.ax.add_patch(poly) poly.set_facecolor('none') poly.set_edgecolor('black') all_plots.polygon = poly # add the polygon pass # Make the inset contour newax = c_big.ax.figure.add_axes([0, 0, 0.5, 0.25]) c_inset = newax.contourf(lons, lats, elevation, **contourProps) all_plots.inset = c_inset # add the inset # Get the corners of the "big" contour ll, ul, lr, ur = c_big.ax.get_position().corners() # Set the width and height of the inset, and position it # inset_width = (inset_bounds[1] - inset_bounds[0])/3.0 # inset_height = (inset_bounds[3] - inset_bounds[2])/3.0 inset_width = 0.2 inset_height = 0.15 new_pos = [lr[0] - inset_width, lr[1], inset_width, inset_height] c_inset.ax.set_position(new_pos) # Next, "zoom" for the inset: _new_lim = c_inset.ax.set_xlim(lon_poly) _new_lim = c_inset.ax.set_ylim(lat_poly) # Modify ticks of the inset c_inset.ax.tick_params(labelbottom=False, labelleft=False) c_inset.ax.tick_params(bottom=False, left=False) # Finally, add the lines. # Get the lower left/upper right of the polygon and inset ll_poly = [lon_poly[0], lat_poly[0]] ur_poly = [lon_poly[1], lat_poly[1]] ll_inset, _, _, ur_inset = c_inset.ax.get_position().corners() # Now, add the lines patch_props = { 'coordsA': 'data', 'axesA': c_big.ax, 'coordsB': 'figure fraction', 'axesB': c_inset.ax } line1 = ConnectionPatch(xyA=ll_poly, xyB=ll_inset, **patch_props) _null = c_big.ax.add_patch(line1) line2 = ConnectionPatch(xyA=ur_poly, xyB=ur_inset, **patch_props) _null = c_big.ax.add_patch(line2) all_plots.lines = [line1, line2] return all_plots pass
def plot_planform(c_r, c_k, c_t, b_k, b, Lambda_le_1, Lambda_le_2, *args, **kwargs): fig = plt.subplots(figsize=(9, 9)) # optional arguments c_mac = kwargs.get('mac', None) X_le_mac = kwargs.get('X_le_mac', None) Y_mac = kwargs.get('Y_mac', None) X_ac = kwargs.get('X_ac', None) xLineWing = [0, b_k / 2, b / 2, b / 2, b_k / 2, 0] dy_k = (b_k / 2) * math.tan(Lambda_le_1) dy = dy_k + (b / 2 - b_k / 2) * math.tan(Lambda_le_2) yLineWing = [0, dy_k, dy, dy + c_t, dy_k + c_k, c_r] # planform lineWing, = plt.plot(xLineWing, yLineWing, 'k-') plt.scatter(xLineWing, yLineWing, marker='o', s=40) # centerline centerLine, = plt.plot([0, 0], [-0.2 * c_r, 2.1 * c_r], 'b') centerLine.set_dashes([8, 4, 2, 4]) # c/4 line pC4r = [0, 0.25 * c_r] pC4k = [b_k / 2, dy_k + 0.25 * c_k] pC4t = [b / 2, dy + 0.25 * c_t] quarterChordLine, = plt.plot([pC4r[0], pC4k[0], pC4t[0]], [pC4r[1], pC4k[1], pC4t[1]], 'k--') plt.scatter([pC4r[0], pC4k[0], pC4t[0]], [pC4r[1], pC4k[1], pC4t[1]], marker='o', s=40) if ('mac' in kwargs) and ('X_le_mac' in kwargs) and ('Y_mac' in kwargs): c_mac = kwargs['mac'] X_le_mac = kwargs['X_le_mac'] Y_mac = kwargs['Y_mac'] #print(mac) #print(X_le_mac) #print(Y_mac) lineMAC, = plt.plot([Y_mac, Y_mac], [X_le_mac, X_le_mac + c_mac], color="red", linewidth=2.5, linestyle="-") lineMAC.set_dashes([1000, 1]) # HUUUUGE lineLEMAC, = plt.plot([0, b / 2], [X_le_mac, X_le_mac], color="orange", linewidth=1.5, linestyle="-") lineLEMAC.set_dashes([10, 2]) lineTEMAC, = plt.plot([0, b / 2], [X_le_mac + c_mac, X_le_mac + c_mac], color="orange", linewidth=1.5, linestyle="-") lineTEMAC.set_dashes([10, 2]) plt.scatter(Y_mac, X_le_mac, marker='o', s=40) ax = plt.gca() # gca stands for 'get current axis' ax.annotate(r'$(Y_{\bar{c}},X_{\mathrm{le},\bar{c}}) = ' + r'( {0:.3}'.format(Y_mac) + r'\,\mathrm{m}' + r',\,{0:.3}'.format(X_le_mac) + r'\,\mathrm{m} )$', xy=(Y_mac, X_le_mac), xycoords='data', xytext=(20, 30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # if ('X_le_r_eq' in kwargs) and ('c_r_eq' in kwargs): X_le_r_eq = kwargs['X_le_r_eq'] c_r_eq = kwargs['c_r_eq'] vertices = [(0, X_le_r_eq)] + [(b / 2, dy)] + [(b / 2, dy + c_t)] + [ (0, X_le_r_eq + c_r_eq) ] poly = Polygon(vertices, facecolor="yellow", alpha=0.5) poly.set_edgecolor("brown") poly.set_linewidth(2) ax0 = plt.gca() # gca stands for 'get current axis' ax0.add_patch(poly) if 'X_ac' in kwargs: X_ac = kwargs['X_ac'] #print(X_ac) plt.scatter(0, X_ac, marker='o', s=40) lineAC, = plt.plot([0, b / 2], [X_ac, X_ac], color="brown", linewidth=3.5, linestyle="-") lineAC.set_dashes([10, 2.5, 3, 2.5]) ax = plt.gca() # gca stands for 'get current axis' ax.annotate(r'$X_{\mathrm{ac,W}} = ' + r'{0:.3}'.format(X_ac) + r'\,\mathrm{m} $', xy=(b / 2, X_ac), xycoords='data', xytext=(20, 30), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # plt.axis('equal') # xmajorLocator = MultipleLocator(2.0) # xmajorFormatter = FormatStrFormatter('%.1f') # xminorLocator = MultipleLocator(4) # ax = plt.gca() # gca stands for 'get current axis' # ax.xaxis.set_major_locator(xmajorLocator) # ax.xaxis.set_major_formatter(xmajorFormatter) # # for the minor ticks, use no labels; default NullFormatter # ax.xaxis.set_minor_locator(xminorLocator) plt.axis([-0.02 * b / 2, 1.1 * b / 2, -0.05 * c_r, 1.1 * (dy + c_t)]) plt.gca().invert_yaxis() plt.title('Wing planform', fontsize=16) plt.xlabel('$y$ (m)', fontsize=16) plt.ylabel('$X$ (m)', fontsize=16) # Moving spines ax = plt.gca() # gca stands for 'get current axis' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('outward', 10)) # outward by 10 points ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', -0.07 * b / 2)) plt.show()
def onclick(self,event): # Disable click events if using the zoom & pan modes. if fig.canvas.widgetlock.locked(): return if event.button==1: # Left-click on plot = add a point if axplot.contains(event)[0] and self.mode != 'done': x = event.xdata y = event.ydata self.offsets.append((x,y)) self.points.set_offsets(self.offsets) if len(self.offsets)==1 : axplot.add_collection(self.points) self.update() # Right-click on wedge = halve the lower colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(clims[0]/2.0,clims[1]) self.update() elif event.button==2: # Middle-click = delete last created point if axplot.contains(event)[0] and len(self.offsets)>0 \ and self.mode != 'done': self.offsets.pop(-1) if len(self.offsets)==0: self.points.remove() else: self.points.set_offsets(self.offsets) self.update() # Middle-click on wedge = reset the colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(zmin,zmax) self.update() if event.button==3: # Right-click on plot = complete the polygon if axplot.contains(event)[0] and len(self.offsets)>2 \ and self.mode != 'done': cpoly = Polygon(self.offsets, animated=False,linewidth=2.0) if self.mode == 'src': cpoly.set_edgecolor('white') cpoly.set_facecolor('none') elif self.mode == 'sky': cpoly.set_edgecolor('yellow') cpoly.set_facecolor('none') elif self.mode == 'exc': cpoly.set_edgecolor('black') cpoly.set_facecolor('none') self.apertures.append(axplot.add_patch(cpoly)) self.update('complete') # Left-click on wedge = halve the upper colour clip if cbar.ax.contains(event)[0]: clims = cax.get_clim() cax.set_clim(clims[0],clims[1]/2.0) self.update()